Repository: namkazt/PinBox Branch: master Commit: 8a7a8e61be28 Files: 407 Total size: 3.3 MB Directory structure: gitextract_jvazmwrt/ ├── .github/ │ ├── ISSUE_TEMPLATE.md │ └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── LICENSE ├── PinBox/ │ ├── PinBox/ │ │ ├── Makefile │ │ ├── PinBox.rsf │ │ ├── PinBox.vcxproj │ │ ├── PinBox.vcxproj.filters │ │ ├── build-cia.bat │ │ ├── create-smdh.bat │ │ ├── include/ │ │ │ ├── Anim.h │ │ │ ├── Color.h │ │ │ ├── ConfigManager.h │ │ │ ├── HubItem.h │ │ │ ├── Logger.h │ │ │ ├── Mutex.h │ │ │ ├── PPAudio.h │ │ │ ├── PPDecoder.h │ │ │ ├── PPGraphics.h │ │ │ ├── PPMessage.h │ │ │ ├── PPSession.h │ │ │ ├── PPSessionManager.h │ │ │ ├── PPUI.h │ │ │ ├── constant.h │ │ │ ├── easing.h │ │ │ ├── lodepng.h │ │ │ └── yuv_rgb.h │ │ ├── source/ │ │ │ ├── ConfigManager.cpp │ │ │ ├── Mutex.cpp │ │ │ ├── PPAudio.cpp │ │ │ ├── PPDecoder.cpp │ │ │ ├── PPGraphics.cpp │ │ │ ├── PPMessage.cpp │ │ │ ├── PPSession.cpp │ │ │ ├── PPSessionManager.cpp │ │ │ ├── PPUI.cpp │ │ │ ├── easing.cpp │ │ │ ├── lodepng.cpp │ │ │ ├── main.cpp │ │ │ ├── vshader.v.pica │ │ │ └── yuv_rgb.c │ │ └── tools/ │ │ └── citra/ │ │ ├── README.md │ │ └── license.txt │ └── PinBox.sln ├── PinBoxServer/ │ ├── Check-Pinbox-Firewall-Rules.bat │ ├── PinBoxServer/ │ │ ├── AudioStreamSession.cpp │ │ ├── AudioStreamSession.h │ │ ├── Check-Pinbox-Firewall-Rules.bat │ │ ├── HubItem.h │ │ ├── InputStreamSession.cpp │ │ ├── InputStreamSession.h │ │ ├── PPClientSession.cpp │ │ ├── PPClientSession.h │ │ ├── PPMessage.cpp │ │ ├── PPMessage.h │ │ ├── PPServer.cpp │ │ ├── PPServer.h │ │ ├── PinBoxServer.cpp │ │ ├── PinBoxServer.vcxproj │ │ ├── PinBoxServer.vcxproj.filters │ │ ├── ScreenCaptureSession.cpp │ │ ├── ScreenCaptureSession.h │ │ ├── ServerConfig.cpp │ │ ├── ServerConfig.h │ │ ├── UIMainWindow.cpp │ │ ├── UIMainWindow.h │ │ ├── const.h │ │ ├── hub.cfg │ │ ├── input.cfg │ │ ├── server.cfg │ │ ├── stdafx.cpp │ │ ├── stdafx.h │ │ ├── targetver.h │ │ └── winmain-inl.h │ └── PinBoxServer.sln ├── PinBoxTestProject/ │ ├── PinBoxTestProject/ │ │ ├── PPDecoder.cpp │ │ ├── PPDecoder.h │ │ ├── PPMessage.cpp │ │ ├── PPMessage.h │ │ ├── PPNetwork.cpp │ │ ├── PPNetwork.h │ │ ├── PPSession.cpp │ │ ├── PPSession.h │ │ ├── PPSessionManager.cpp │ │ ├── PPSessionManager.h │ │ ├── PinBoxTestProject.vcxproj │ │ ├── PinBoxTestProject.vcxproj.filters │ │ ├── main.cpp │ │ ├── yuv_rgb.c │ │ └── yuv_rgb.h │ └── PinBoxTestProject.sln ├── README.md ├── ThirdParty/ │ ├── FakeInput/ │ │ ├── LICENSE │ │ └── src/ │ │ ├── actions/ │ │ │ ├── action.hpp │ │ │ ├── actions.hpp │ │ │ ├── actionsequence.cpp │ │ │ ├── actionsequence.hpp │ │ │ ├── commandaction.cpp │ │ │ ├── commandaction.hpp │ │ │ ├── keyaction.cpp │ │ │ ├── keyaction.hpp │ │ │ ├── mouseaction.cpp │ │ │ ├── mouseaction.hpp │ │ │ ├── waitaction.cpp │ │ │ └── waitaction.hpp │ │ ├── config.hpp │ │ ├── config.hpp.cmake │ │ ├── display_unix.cpp │ │ ├── display_unix.hpp │ │ ├── fakeinput.hpp │ │ ├── key.hpp │ │ ├── key_base.cpp │ │ ├── key_base.hpp │ │ ├── key_unix.cpp │ │ ├── key_unix.hpp │ │ ├── key_win.cpp │ │ ├── key_win.hpp │ │ ├── keyboard.cpp │ │ ├── keyboard.hpp │ │ ├── keyboard_unix.cpp │ │ ├── keyboard_win.cpp │ │ ├── mapper.hpp │ │ ├── mapper_unix.cpp │ │ ├── mapper_win.cpp │ │ ├── mouse.hpp │ │ ├── mouse_unix.cpp │ │ ├── mouse_win.cpp │ │ ├── system.hpp │ │ ├── system_unix.cpp │ │ ├── system_win.cpp │ │ └── types.hpp │ ├── ViGEm/ │ │ ├── Debug (dynamic)/ │ │ │ ├── ViGEmClient.exp │ │ │ └── ViGEmClient.lib │ │ ├── Debug (static)/ │ │ │ └── ViGEmClient.lib │ │ ├── Include/ │ │ │ ├── ViGEmBusDriver.h │ │ │ ├── ViGEmBusShared.h │ │ │ ├── ViGEmClient.h │ │ │ ├── ViGEmCommon.h │ │ │ ├── ViGEmUtil.h │ │ │ ├── XInputOverrides.h │ │ │ └── XnaGuardianShared.h │ │ ├── LICENSE │ │ ├── Release (dynamic)/ │ │ │ ├── ViGEmClient.exp │ │ │ └── ViGEmClient.lib │ │ └── Release (static)/ │ │ └── ViGEmClient.lib │ ├── ffmpeg/ │ │ ├── LICENSE.txt │ │ ├── README.txt │ │ ├── examples/ │ │ │ ├── Makefile │ │ │ ├── README │ │ │ ├── avio_dir_cmd.c │ │ │ ├── avio_reading.c │ │ │ ├── decode_audio.c │ │ │ ├── decode_video.c │ │ │ ├── demuxing_decoding.c │ │ │ ├── encode_audio.c │ │ │ ├── encode_video.c │ │ │ ├── extract_mvs.c │ │ │ ├── filter_audio.c │ │ │ ├── filtering_audio.c │ │ │ ├── filtering_video.c │ │ │ ├── http_multiclient.c │ │ │ ├── hw_decode.c │ │ │ ├── metadata.c │ │ │ ├── muxing.c │ │ │ ├── qsvdec.c │ │ │ ├── remuxing.c │ │ │ ├── resampling_audio.c │ │ │ ├── scaling_video.c │ │ │ ├── transcode_aac.c │ │ │ ├── transcoding.c │ │ │ ├── vaapi_encode.c │ │ │ └── vaapi_transcode.c │ │ ├── include/ │ │ │ ├── libavcodec/ │ │ │ │ ├── ac3_parser.h │ │ │ │ ├── adts_parser.h │ │ │ │ ├── avcodec.h │ │ │ │ ├── avdct.h │ │ │ │ ├── avfft.h │ │ │ │ ├── d3d11va.h │ │ │ │ ├── dirac.h │ │ │ │ ├── dv_profile.h │ │ │ │ ├── dxva2.h │ │ │ │ ├── jni.h │ │ │ │ ├── mediacodec.h │ │ │ │ ├── qsv.h │ │ │ │ ├── vaapi.h │ │ │ │ ├── vdpau.h │ │ │ │ ├── version.h │ │ │ │ ├── videotoolbox.h │ │ │ │ ├── vorbis_parser.h │ │ │ │ └── xvmc.h │ │ │ ├── libavdevice/ │ │ │ │ ├── avdevice.h │ │ │ │ └── version.h │ │ │ ├── libavfilter/ │ │ │ │ ├── avfilter.h │ │ │ │ ├── buffersink.h │ │ │ │ ├── buffersrc.h │ │ │ │ └── version.h │ │ │ ├── libavformat/ │ │ │ │ ├── avformat.h │ │ │ │ ├── avio.h │ │ │ │ └── version.h │ │ │ ├── libavutil/ │ │ │ │ ├── adler32.h │ │ │ │ ├── aes.h │ │ │ │ ├── aes_ctr.h │ │ │ │ ├── attributes.h │ │ │ │ ├── audio_fifo.h │ │ │ │ ├── avassert.h │ │ │ │ ├── avconfig.h │ │ │ │ ├── avstring.h │ │ │ │ ├── avutil.h │ │ │ │ ├── base64.h │ │ │ │ ├── blowfish.h │ │ │ │ ├── bprint.h │ │ │ │ ├── bswap.h │ │ │ │ ├── buffer.h │ │ │ │ ├── camellia.h │ │ │ │ ├── cast5.h │ │ │ │ ├── channel_layout.h │ │ │ │ ├── common.h │ │ │ │ ├── cpu.h │ │ │ │ ├── crc.h │ │ │ │ ├── des.h │ │ │ │ ├── dict.h │ │ │ │ ├── display.h │ │ │ │ ├── downmix_info.h │ │ │ │ ├── encryption_info.h │ │ │ │ ├── error.h │ │ │ │ ├── eval.h │ │ │ │ ├── ffversion.h │ │ │ │ ├── fifo.h │ │ │ │ ├── file.h │ │ │ │ ├── frame.h │ │ │ │ ├── hash.h │ │ │ │ ├── hmac.h │ │ │ │ ├── hwcontext.h │ │ │ │ ├── hwcontext_cuda.h │ │ │ │ ├── hwcontext_d3d11va.h │ │ │ │ ├── hwcontext_drm.h │ │ │ │ ├── hwcontext_dxva2.h │ │ │ │ ├── hwcontext_mediacodec.h │ │ │ │ ├── hwcontext_qsv.h │ │ │ │ ├── hwcontext_vaapi.h │ │ │ │ ├── hwcontext_vdpau.h │ │ │ │ ├── hwcontext_videotoolbox.h │ │ │ │ ├── imgutils.h │ │ │ │ ├── intfloat.h │ │ │ │ ├── intreadwrite.h │ │ │ │ ├── lfg.h │ │ │ │ ├── log.h │ │ │ │ ├── lzo.h │ │ │ │ ├── macros.h │ │ │ │ ├── mastering_display_metadata.h │ │ │ │ ├── mathematics.h │ │ │ │ ├── md5.h │ │ │ │ ├── mem.h │ │ │ │ ├── motion_vector.h │ │ │ │ ├── murmur3.h │ │ │ │ ├── opt.h │ │ │ │ ├── parseutils.h │ │ │ │ ├── pixdesc.h │ │ │ │ ├── pixelutils.h │ │ │ │ ├── pixfmt.h │ │ │ │ ├── random_seed.h │ │ │ │ ├── rational.h │ │ │ │ ├── rc4.h │ │ │ │ ├── replaygain.h │ │ │ │ ├── ripemd.h │ │ │ │ ├── samplefmt.h │ │ │ │ ├── sha.h │ │ │ │ ├── sha512.h │ │ │ │ ├── spherical.h │ │ │ │ ├── stereo3d.h │ │ │ │ ├── tea.h │ │ │ │ ├── threadmessage.h │ │ │ │ ├── time.h │ │ │ │ ├── timecode.h │ │ │ │ ├── timestamp.h │ │ │ │ ├── tree.h │ │ │ │ ├── twofish.h │ │ │ │ ├── version.h │ │ │ │ └── xtea.h │ │ │ ├── libpostproc/ │ │ │ │ ├── postprocess.h │ │ │ │ └── version.h │ │ │ ├── libswresample/ │ │ │ │ ├── swresample.h │ │ │ │ └── version.h │ │ │ └── libswscale/ │ │ │ ├── swscale.h │ │ │ └── version.h │ │ └── lib/ │ │ ├── avcodec-58.def │ │ ├── avcodec.lib │ │ ├── avdevice-58.def │ │ ├── avdevice.lib │ │ ├── avfilter-7.def │ │ ├── avfilter.lib │ │ ├── avformat-58.def │ │ ├── avformat.lib │ │ ├── avutil-56.def │ │ ├── avutil.lib │ │ ├── libavcodec.dll.a │ │ ├── libavdevice.dll.a │ │ ├── libavfilter.dll.a │ │ ├── libavformat.dll.a │ │ ├── libavutil.dll.a │ │ ├── libpostproc.dll.a │ │ ├── libswresample.dll.a │ │ ├── libswscale.dll.a │ │ ├── postproc-55.def │ │ ├── postproc.lib │ │ ├── swresample-3.def │ │ ├── swresample.lib │ │ ├── swscale-5.def │ │ └── swscale.lib │ ├── libopusenc/ │ │ ├── AUTHORS │ │ ├── include/ │ │ │ └── opusenc.h │ │ ├── src/ │ │ │ ├── arch.h │ │ │ ├── ogg_packer.c │ │ │ ├── ogg_packer.h │ │ │ ├── opus_header.c │ │ │ ├── opus_header.h │ │ │ ├── opusenc.c │ │ │ ├── picture.c │ │ │ ├── picture.h │ │ │ ├── resample.c │ │ │ ├── resample_sse.h │ │ │ ├── speex_resampler.h │ │ │ └── stack_alloc.h │ │ └── win32/ │ │ └── config.h │ ├── loopback/ │ │ ├── cleanup.h │ │ ├── common.h │ │ ├── guid.cpp │ │ ├── log.h │ │ ├── loopback-capture.cpp │ │ ├── loopback-capture.h │ │ ├── main.cpp │ │ ├── prefs.cpp │ │ └── prefs.h │ ├── opus-1.2.1/ │ │ ├── AUTHORS │ │ ├── COPYING │ │ ├── INSTALL │ │ ├── include/ │ │ │ ├── opus.h │ │ │ ├── opus_custom.h │ │ │ ├── opus_defines.h │ │ │ ├── opus_multistream.h │ │ │ └── opus_types.h │ │ └── src/ │ │ ├── analysis.c │ │ ├── analysis.h │ │ ├── mlp.c │ │ ├── mlp.h │ │ ├── mlp_data.c │ │ ├── opus.c │ │ ├── opus_compare.c │ │ ├── opus_decoder.c │ │ ├── opus_demo.c │ │ ├── opus_encoder.c │ │ ├── opus_multistream.c │ │ ├── opus_multistream_decoder.c │ │ ├── opus_multistream_encoder.c │ │ ├── opus_private.h │ │ ├── repacketizer.c │ │ ├── repacketizer_demo.c │ │ └── tansig_table.h │ ├── opusfile-0.9/ │ │ ├── AUTHORS │ │ ├── include/ │ │ │ └── opusfile.h │ │ ├── src/ │ │ │ ├── http.c │ │ │ ├── info.c │ │ │ ├── internal.c │ │ │ ├── internal.h │ │ │ ├── opusfile.c │ │ │ ├── stream.c │ │ │ ├── wincerts.c │ │ │ └── winerrno.h │ │ └── win32/ │ │ └── VS2015/ │ │ └── Win32/ │ │ └── Release-NoHTTP/ │ │ └── opusfile.lib │ ├── screen_capture_lite/ │ │ └── include/ │ │ └── ScreenCapture.h │ └── screen_capture_lite - Copy/ │ ├── LICENSE │ ├── ScreenCapture.h │ ├── include/ │ │ ├── SCCommon.h │ │ ├── ScreenCapture.h │ │ ├── ThreadManager.h │ │ ├── ios/ │ │ │ ├── CGFrameProcessor.h │ │ │ ├── NSMouseCapture.h │ │ │ └── NSMouseProcessor.h │ │ ├── linux/ │ │ │ ├── X11FrameProcessor.h │ │ │ └── X11MouseProcessor.h │ │ └── windows/ │ │ ├── DXFrameProcessor.h │ │ ├── GDIFrameProcessor.h │ │ ├── GDIHelpers.h │ │ ├── GDIMouseProcessor.h │ │ └── GDIWindowProcessor.h │ └── src/ │ ├── SCCommon.cpp │ ├── ScreenCapture.cpp │ ├── ThreadManager.cpp │ ├── ios/ │ │ ├── CGFrameProcessor.cpp │ │ ├── GetMonitors.cpp │ │ ├── GetWindows.cpp │ │ ├── NSMouseCapture.m │ │ ├── NSMouseProcessor.cpp │ │ └── ThreadRunner.cpp │ ├── linux/ │ │ ├── GetMonitors.cpp │ │ ├── GetWindows.cpp │ │ ├── ThreadRunner.cpp │ │ ├── X11FrameProcessor.cpp │ │ └── X11MouseProcessor.cpp │ └── windows/ │ ├── DXFrameProcessor.cpp │ ├── GDIFrameProcessor.cpp │ ├── GDIMouseProcessor.cpp │ ├── GDIWindowProcessor.cpp │ ├── GetMonitors.cpp │ ├── GetWindows.cpp │ └── ThreadRunner.cpp └── _config.yml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ Please, set a title for the issue that starts with "BUG" or "FEATURE REQUEST" accordingly. Use [the Pinbox Discord Server](https://discord.gg/9Qae7fT) for supporting issues. ## Expected Behavior ## Current Behavior ## Possible Solution ## Steps to Reproduce 1. 2. 3. 4. ## Context (Environment) ## Detailed Description ## Possible Implementation ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ Please, set a title for the pull request that starts with "BUG" or "FEATURE REQUEST" accordingly. ## Description ## Related Issue ## Motivation and Context ## How Has This Been Tested? ## Screenshots (if appropriate): ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ #============================================== # 3DS #============================================== *.d *.o *.elf *.3dsx #============================================== # PinBox #============================================== PinBox/PinBox/build/ PinBox/PinBox/data/ #============================================== # PinBoxServer #============================================== PinBoxServer/Debug/ PinBoxServer/Release/ #============================================== # Other File #============================================== *.rar *.flv *.mp4 *.cia *.smdh PinBox/PinBox/Pre-Built/PinBox.smdh ThirdParty/xinput1_3.dll ThirdParty/x360ce.ini ================================================ FILE: LICENSE ================================================ GLWT(Good Luck With That) Public License Copyright (c) Everyone, except Author Everyone is permitted to copy, distribute, modify, merge, sell, publish, sublicense or whatever they want with this software but at their OWN RISK. Preamble The author has absolutely no clue what the code in this project does. It might just work or not, there is no third option. GOOD LUCK WITH THAT PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION, AND MODIFICATION 0. You just DO WHATEVER YOU WANT TO as long as you NEVER LEAVE A TRACE TO TRACK THE AUTHOR of the original product to blame for or hold responsible. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Good luck and Godspeed. ================================================ FILE: PinBox/PinBox/Makefile ================================================ export DEVKITPRO = /c/devkitPro export DEVKITARM = /c/devkitPro/devkitARM #--------------------------------------------------------------------------------- .SUFFIXES: #--------------------------------------------------------------------------------- ifeq ($(strip $(DEVKITARM)),) $(error "Please set DEVKITARM in your environment. export DEVKITARM=devkitARM") endif TOPDIR ?= $(CURDIR) include $(DEVKITARM)/3ds_rules #--------------------------------------------------------------------------------- # TARGET is the name of the output # BUILD is the directory where object files & intermediate files will be placed # SOURCES is a list of directories containing source code # DATA is a list of directories containing data files # INCLUDES is a list of directories containing header files # # NO_SMDH: if set to anything, no SMDH file is generated. # ROMFS is the directory which contains the RomFS, relative to the Makefile (Optional) # APP_TITLE is the name of the app stored in the SMDH file (Optional) # APP_DESCRIPTION is the description of the app stored in the SMDH file (Optional) # APP_AUTHOR is the author of the app stored in the SMDH file (Optional) # ICON is the filename of the icon (.png), relative to the project folder. # If not set, it attempts to use one of the following (in this order): # - .png # - icon.png # - /default_icon.png #--------------------------------------------------------------------------------- TARGET := PinBox BUILD := build SOURCES := source DATA := data INCLUDES := include ICON := assets/icon.png ROMFS := romfs #--------------------------------------------------------------------------------- APP_TITLE := PinBox APP_DESCRIPTION := 3DS Client - PC Desktop Streaming APP_AUTHOR := Namkazt APP_PRODUCT_CODE := CTR-P-PINBOX APP_UNIQUE_ID := 0x18EF APP_ENCRYPTED := false #--------------------------------------------------------------------------------- # options for code generation #--------------------------------------------------------------------------------- ARCH := -march=armv6k -mtune=mpcore -mtp=soft -mfloat-abi=hard CFLAGS := -ggdb -Wall -Og -mword-relocations -DDEBUG=1 \ -ffunction-sections \ $(ARCH) CFLAGS += $(INCLUDE) -DARM11 -D_3DS CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions -std=gnu++11 -fpermissive -fexceptions -ffast-math ASFLAGS := -g $(ARCH) LDFLAGS = -specs=3dsx.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) LIBS := -lavformat -lavcodec -lavutil -lswscale -lswresample -lconfig -lcitro3dd -lctrud -lz -lm #--------------------------------------------------------------------------------- # list of directories containing libraries, this must be the top level containing # include and lib #--------------------------------------------------------------------------------- ADDITION_LIBS := $(DEVKITPRO)/libwebp $(DEVKITPRO)/libcitro3d LIBDIRS := $(CTRULIB) $(PORTLIBS) $(ADDITION_LIBS) #--------------------------------------------------------------------------------- # no real need to edit anything past this point unless you need to add additional # rules for different file extensions #--------------------------------------------------------------------------------- ifneq ($(BUILD),$(notdir $(CURDIR))) #--------------------------------------------------------------------------------- export OUTPUT := $(CURDIR)/$(TARGET) export TOPDIR := $(CURDIR) export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ $(foreach dir,$(DATA),$(CURDIR)/$(dir)) export DEPSDIR := $(CURDIR)/$(BUILD) CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) PICAFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.v.pica))) SHLISTFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.shlist))) BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) #--------------------------------------------------------------------------------- # use CXX for linking C++ projects, CC for standard C #--------------------------------------------------------------------------------- ifeq ($(strip $(CPPFILES)),) #--------------------------------------------------------------------------------- export LD := $(CC) #--------------------------------------------------------------------------------- else #--------------------------------------------------------------------------------- export LD := $(CXX) #--------------------------------------------------------------------------------- endif #--------------------------------------------------------------------------------- export OFILES_SOURCES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) export OFILES_BIN := $(addsuffix .o,$(BINFILES)) \ $(PICAFILES:.v.pica=.shbin.o) $(SHLISTFILES:.shlist=.shbin.o) export OFILES := $(OFILES_BIN) $(OFILES_SOURCES) export HFILES := $(PICAFILES:.v.pica=_shbin.h) $(SHLISTFILES:.shlist=_shbin.h) $(addsuffix .h,$(subst .,_,$(BINFILES))) export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ -I$(CURDIR)/$(BUILD) export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) ifeq ($(strip $(ICON)),) icons := $(wildcard *.png) ifneq (,$(findstring $(TARGET).png,$(icons))) export APP_ICON := $(TOPDIR)/assets/$(TARGET).png else ifneq (,$(findstring icon.png,$(icons))) export APP_ICON := $(TOPDIR)/assets/icon.png endif endif else export APP_ICON := $(TOPDIR)/assets/$(ICON) endif ifeq ($(strip $(NO_SMDH)),) export _3DSXFLAGS += --smdh=$(CURDIR)/$(TARGET).smdh endif ifneq ($(ROMFS),) export _3DSXFLAGS += --romfs=$(CURDIR)/$(ROMFS) endif .PHONY: $(BUILD) clean all #--------------------------------------------------------------------------------- all: $(BUILD) $(BUILD): @[ -d $@ ] || mkdir -p $@ @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile #--------------------------------------------------------------------------------- clean: @echo clean ... @rm -fr $(BUILD) $(TARGET).3dsx $(TARGET).elf #--------------------------------------------------------------------------------- $(TARGET)-strip.elf: $(BUILD) @$(STRIP) $(TARGET).elf -o $(TARGET)-strip.elf #--------------------------------------------------------------------------------- cci: $(TARGET)-strip.elf @makerom -f cci -rsf $(CURDIR)/$(TARGET).rsf -target d -exefslogo -elf $(TARGET)-strip.elf -o $(TARGET).3ds #--------------------------------------------------------------------------------- cia: $(TARGET)-strip.elf @$(CURDIR)/tools/makerom32.exe -f cia -o $(TARGET).cia -elf $(TARGET)-strip.elf -rsf $(CURDIR)/$(TARGET).rsf -exefslogo -target t #--------------------------------------------------------------------------------- netlink: $(BUILD) $(DEVKITARM)/bin/3dslink.exe --address 192.168.50.231 $(TARGET).3dsx #--------------------------------------------------------------------------------- citra: $(BUILD) $(CURDIR)/tools/citra/citra.exe $(TARGET).3dsx #--------------------------------------------------------------------------------- citra-qt: $(BUILD) $(CURDIR)/tools/citra/citra-qt.exe $(TARGET).3dsx #--------------------------------------------------------------------------------- else DEPENDS := $(OFILES:.o=.d) #--------------------------------------------------------------------------------- # main targets #--------------------------------------------------------------------------------- ifeq ($(strip $(NO_SMDH)),) $(OUTPUT).3dsx : $(OUTPUT).elf $(OUTPUT).smdh else $(OUTPUT).3dsx : $(OUTPUT).elf endif $(OFILES_SOURCES) : $(HFILES) $(OUTPUT).elf : $(OFILES) #--------------------------------------------------------------------------------- # you need a rule like this for each extension you use as binary data #--------------------------------------------------------------------------------- %.bin.o %_bin.h : %.bin #--------------------------------------------------------------------------------- @echo $(notdir $<) @$(bin2o) #--------------------------------------------------------------------------------- %.ttf.o : %.ttf #--------------------------------------------------------------------------------- @echo $(notdir $<) @$(bin2o) #--------------------------------------------------------------------------------- %.png.o : %.png #--------------------------------------------------------------------------------- @echo $(notdir $<) @$(bin2o) #--------------------------------------------------------------------------------- # rules for assembling GPU shaders #--------------------------------------------------------------------------------- define shader-as $(eval CURBIN := $*.shbin) $(eval DEPSFILE := $(DEPSDIR)/$*.shbin.d) echo "$(CURBIN).o: $< $1" > $(DEPSFILE) echo "extern const u8" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"_end[];" > `(echo $(CURBIN) | tr . _)`.h echo "extern const u8" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`"[];" >> `(echo $(CURBIN) | tr . _)`.h echo "extern const u32" `(echo $(CURBIN) | sed -e 's/^\([0-9]\)/_\1/' | tr . _)`_size";" >> `(echo $(CURBIN) | tr . _)`.h picasso -o $(CURBIN) $1 bin2s $(CURBIN) | $(AS) -o $*.shbin.o endef %.shbin.o %_shbin.h : %.v.pica %.g.pica @echo $(notdir $^) @$(call shader-as,$^) %.shbin.o %_shbin.h : %.v.pica @echo $(notdir $<) @$(call shader-as,$<) %.shbin.o %_shbin.h : %.shlist @echo $(notdir $<) @$(call shader-as,$(foreach file,$(shell cat $<),$(dir $<)$(file))) -include $(DEPENDS) #--------------------------------------------------------------------------------------- endif #--------------------------------------------------------------------------------------- ================================================ FILE: PinBox/PinBox/PinBox.rsf ================================================ BasicInfo: Title : PINBOX r0.2.1 ProductCode : CTR-P-PINBOX ContentType : Application # Application / SystemUpdate / Manual / Child / Trial Logo : Nintendo # Nintendo / Licensed / Distributed / iQue / iQueForSystem RomFs: RootPath: $(APP_ROMFS) TitleInfo: Category : Application UniqueId : 0x18EF Option: UseOnSD : true # true if App is to be installed to SD FreeProductCode : true # Removes limitations on ProductCode MediaFootPadding : false # If true CCI files are created with padding EnableCrypt : false #$(APP_ENCRYPTED) # Enables encryption for NCCH and CIA EnableCompress : true # Compresses where applicable (currently only exefs:/.code) AccessControlInfo: CoreVersion : 2 # Exheader Format Version DescVersion : 2 # Minimum Required Kernel Version (below is for 4.5.0) ReleaseKernelMajor : "02" ReleaseKernelMinor : "33" # ExtData UseExtSaveData : false # enables ExtData #ExtSaveDataId : 0x300 # only set this when the ID is different to the UniqueId # FS:USER Archive Access Permissions # Uncomment as required FileSystemAccess: - CategorySystemApplication - CategoryHardwareCheck - CategoryFileSystemTool - Debug - TwlCardBackup - TwlNandData - Boss - DirectSdmc - Core - CtrNandRo - CtrNandRw - CtrNandRoWrite - CategorySystemSettings - CardBoard - ExportImportIvs - DirectSdmcWrite - SwitchCleanup - SaveDataMove - Shop - Shell - CategoryHomeMenu IoAccessControl: - FsMountNand - FsMountNandRoWrite - FsMountTwln - FsMountWnand - FsMountCardSpi - UseSdif3 - CreateSeed - UseCardSpi # Process Settings MemoryType : Application # Application/System/Base SystemMode : $(APP_SYSTEM_MODE) # 64MB(Default)/96MB/80MB/72MB/32MB IdealProcessor : 0 AffinityMask : 1 Priority : 16 MaxCpu : 0x9E # Default HandleTableSize : 0x200 DisableDebug : false EnableForceDebug : false CanWriteSharedPage : true CanUsePrivilegedPriority : false CanUseNonAlphabetAndNumber : true PermitMainFunctionArgument : true CanShareDeviceMemory : true RunnableOnSleep : false SpecialMemoryArrange : true # New3DS Exclusive Process Settings SystemModeExt : $(APP_SYSTEM_MODE_EXT) # Legacy(Default)/124MB/178MB Legacy:Use Old3DS SystemMode CpuSpeed : 804MHz # 256MHz(Default)/804MHz EnableL2Cache : true # false(default)/true CanAccessCore2 : true # Virtual Address Mappings IORegisterMapping: - 1ff00000-1ff7ffff # DSP memory MemoryMapping: - 1f000000-1f5fffff:r # VRAM # Accessible SVCs, : SystemCallAccess: ControlMemory: 1 QueryMemory: 2 ExitProcess: 3 GetProcessAffinityMask: 4 SetProcessAffinityMask: 5 GetProcessIdealProcessor: 6 SetProcessIdealProcessor: 7 CreateThread: 8 ExitThread: 9 SleepThread: 10 GetThreadPriority: 11 SetThreadPriority: 12 GetThreadAffinityMask: 13 SetThreadAffinityMask: 14 GetThreadIdealProcessor: 15 SetThreadIdealProcessor: 16 GetCurrentProcessorNumber: 17 Run: 18 CreateMutex: 19 ReleaseMutex: 20 CreateSemaphore: 21 ReleaseSemaphore: 22 CreateEvent: 23 SignalEvent: 24 ClearEvent: 25 CreateTimer: 26 SetTimer: 27 CancelTimer: 28 ClearTimer: 29 CreateMemoryBlock: 30 MapMemoryBlock: 31 UnmapMemoryBlock: 32 CreateAddressArbiter: 33 ArbitrateAddress: 34 CloseHandle: 35 WaitSynchronization1: 36 WaitSynchronizationN: 37 SignalAndWait: 38 DuplicateHandle: 39 GetSystemTick: 40 GetHandleInfo: 41 GetSystemInfo: 42 GetProcessInfo: 43 GetThreadInfo: 44 ConnectToPort: 45 SendSyncRequest1: 46 SendSyncRequest2: 47 SendSyncRequest3: 48 SendSyncRequest4: 49 SendSyncRequest: 50 OpenProcess: 51 OpenThread: 52 GetProcessId: 53 GetProcessIdOfThread: 54 GetThreadId: 55 GetResourceLimit: 56 GetResourceLimitLimitValues: 57 GetResourceLimitCurrentValues: 58 GetThreadContext: 59 Break: 60 OutputDebugString: 61 ControlPerformanceCounter: 62 CreatePort: 71 CreateSessionToPort: 72 CreateSession: 73 AcceptSession: 74 ReplyAndReceive1: 75 ReplyAndReceive2: 76 ReplyAndReceive3: 77 ReplyAndReceive4: 78 ReplyAndReceive: 79 BindInterrupt: 80 UnbindInterrupt: 81 InvalidateProcessDataCache: 82 StoreProcessDataCache: 83 FlushProcessDataCache: 84 StartInterProcessDma: 85 StopDma: 86 GetDmaState: 87 RestartDma: 88 DebugActiveProcess: 96 BreakDebugProcess: 97 TerminateDebugProcess: 98 GetProcessDebugEvent: 99 ContinueDebugEvent: 100 GetProcessList: 101 GetThreadList: 102 GetDebugThreadContext: 103 SetDebugThreadContext: 104 QueryDebugProcessMemory: 105 ReadProcessMemory: 106 WriteProcessMemory: 107 SetHardwareBreakPoint: 108 GetDebugThreadParam: 109 ControlProcessMemory: 112 MapProcessMemory: 113 UnmapProcessMemory: 114 CreateCodeSet: 115 CreateProcess: 117 TerminateProcess: 118 SetProcessResourceLimits: 119 CreateResourceLimit: 120 SetResourceLimitValues: 121 AddCodeSegment: 122 Backdoor: 123 KernelSetState: 124 QueryProcessMemory: 125 # Service List # Maximum 34 services (32 if firmware is prior to 9.6.0) ServiceAccessControl: - APT:U - ac:u - am:net - boss:U - cam:u - cecd:u - cfg:nor - cfg:u - csnd:SND - dsp::DSP - frd:u - fs:USER - gsp::Gpu - gsp::Lcd - hid:USER - http:C - ir:rst - ir:u - ir:USER - mic:u - ndm:u - news:s - nwm::EXT - nwm::UDS - ptm:sysm - ptm:u - pxi:dev - soc:U - ssl:C - y2r:u SystemControlInfo: SaveDataSize: 0KB # Change if the app uses savedata RemasterVersion: 2 StackSize: 0x40000 # Modules that run services listed above should be included below # Maximum 48 dependencies # : Dependency: ac: 0x0004013000002402 #act: 0x0004013000003802 am: 0x0004013000001502 boss: 0x0004013000003402 camera: 0x0004013000001602 cecd: 0x0004013000002602 cfg: 0x0004013000001702 codec: 0x0004013000001802 csnd: 0x0004013000002702 dlp: 0x0004013000002802 dsp: 0x0004013000001a02 friends: 0x0004013000003202 gpio: 0x0004013000001b02 gsp: 0x0004013000001c02 hid: 0x0004013000001d02 http: 0x0004013000002902 i2c: 0x0004013000001e02 ir: 0x0004013000003302 mcu: 0x0004013000001f02 mic: 0x0004013000002002 ndm: 0x0004013000002b02 news: 0x0004013000003502 #nfc: 0x0004013000004002 nim: 0x0004013000002c02 nwm: 0x0004013000002d02 pdn: 0x0004013000002102 ps: 0x0004013000003102 ptm: 0x0004013000002202 #qtm: 0x0004013020004202 ro: 0x0004013000003702 socket: 0x0004013000002e02 spi: 0x0004013000002302 ssl: 0x0004013000002f02 ================================================ FILE: PinBox/PinBox/PinBox.vcxproj ================================================  Citra-QT Win32 Citra-QT x64 Citra Win32 Netlink Win32 Citra x64 Netlink x64 TestClient Win32 TestClient x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01} MakeFileProj 8.1 Makefile true v140 Application true v140 Makefile false v140 Application true v140 Application true v140 Application false v140 v140 Makefile v140 USE_CITRA;CITRA;_DEBUG;$(NMakePreprocessorDefinitions) C:\devkitPro\devkitARM\arm-none-eabi\include;C:\devkitPro\libctru\include;C:\devkitPro\libwebp\include;C:\devkitPro\libimgui\include;include;build;C:\devkitPro\portlibs\armv6k\include;$(IncludePath) make & start make citra make clean all make clean C:\devkitPro\libctru\include;C:\devkitPro\devkitARM\arm-none-eabi\include;include;C:\devkitPro\libwebp\include;build;C:\devkitPro\libimgui\include;C:\devkitPro\portlibs\armv6k\include;$(NMakeIncludeSearchPath) ..\tmp\out\$(Configuration)\ ..\tmp\intermediate\$(Configuration)\ WIN32;_DEBUG;$(NMakePreprocessorDefinitions) C:\devkitPro\devkitARM\arm-none-eabi\include;C:\devkitPro\libctru\include;C:\devkitPro\libwebp\include;C:\devkitPro\libimgui\include;include;build;$(IncludePath) C:\devkitPro\libctru\include;C:\devkitPro\devkitARM\arm-none-eabi\include;include;C:\devkitPro\libwebp\include;build;C:\devkitPro\libimgui\include;$(NMakeIncludeSearchPath) ..\tmp\out\$(Configuration)\ ..\tmp\intermediate\$(Configuration)\ $(NMakePreprocessorDefinitions) C:\devkitPro\devkitARM\arm-none-eabi\include;C:\devkitPro\libctru\include;C:\devkitPro\libwebp\include;C:\devkitPro\libimgui\include;include;build;C:\devkitPro\portlibs\armv6k\include;$(IncludePath) make & start make netlink make clean all make clean C:\devkitPro\libctru\include;C:\devkitPro\devkitARM\arm-none-eabi\include;C:\devkitPro\libwebp\include;include;build;$(NMakeIncludeSearchPath) ..\tmp\out\$(Configuration)\ ..\tmp\intermediate\$(Configuration)\ C:\devkitPro\devkitARM\arm-none-eabi\include;C:\devkitPro\libctru\include;C:\devkitPro\libwebp\include;C:\devkitPro\libimgui\include;include;build;C:\devkitPro\portlibs\armv6k\include;$(IncludePath) USE_CITRA;CITRA;_DEBUG;$(NMakePreprocessorDefinitions) C:\devkitPro\libctru\include;C:\devkitPro\devkitARM\arm-none-eabi\include;include;C:\devkitPro\libwebp\include;build;C:\devkitPro\libimgui\include;C:\devkitPro\portlibs\armv6k\include;$(NMakeIncludeSearchPath) make & start make citra-qt make clean all make clean ================================================ FILE: PinBox/PinBox/PinBox.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Resource Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files ================================================ FILE: PinBox/PinBox/build-cia.bat ================================================ start make clean & make all & make PinBox-strip.elf & make cia ================================================ FILE: PinBox/PinBox/create-smdh.bat ================================================ start smdhtool --create "PinBox" "3DS Client - PC Desktop Streaming" "Namkazt" "E:\3ds\PinBoxStreaming\PinBox\PinBox\assets\icon.png" Pinbox.smdh ================================================ FILE: PinBox/PinBox/include/Anim.h ================================================ #ifndef _PP_ANIM_H_ #define _PP_ANIM_H_ #include #include <3ds/services/am.h> #include <3ds/ndsp/ndsp.h> #include #define TIME_MILISECOND 1Ull #define TIME_SECOND 1000Ull #define TIME_MINUTE 3600000Ull #define TIME_HOUR 216000000Ull class Anim { struct AnimInfo { u32 idx; u64 startTime; u64 duration; float from; float to; easing_functions func; }; }; #endif ================================================ FILE: PinBox/PinBox/include/Color.h ================================================ #ifndef _PP_COLOR_H_ #define _PP_COLOR_H_ #include #define M_MIN(a,b) (((a) < (b)) ? (a) : (b)) #define M_MAX(a,b) (((a) > (b)) ? (a) : (b)) #define M_MIN3(a,b,c) (((a) < (b)) ? (((a) < (c)) ? (a) : (c)) : (((b) < (c)) ? (b) : (c))) #define M_MAX3(a,b,c) (((a) > (b)) ? (((a) > (c)) ? (a) : (c)) : (((b) > (c)) ? (b) : (c))) //TODO: port this // https://github.com/Qix-/color-convert/blob/master/conversions.js // and this https://github.com/Qix-/color/blob/master/index.js#L298 struct Color; #define RGB(r,g,b) Color{r, g, b, 255} #define RGBA(r,g,b,a) Color{r, g, b, a} #define TRANSPARENT Color{0, 0, 0, 0} typedef struct Color { Color() : r(255), g(255), b(255), a(255) {}; Color(uint8_t _r, uint8_t _g, uint8_t _b, uint8_t _a) : r(_r), g(_g), b(_b), a(_a) {}; uint8_t r, g, b, a; float h, l, s, v; u32 toU32() const { return (((a) & 0xFF) << 24) | (((b) & 0xFF) << 16) | (((g) & 0xFF) << 8) | (((r) & 0xFF) << 0); } // type conversions inline void rgb2hsl() { float _r = r / 255.f, _g = g / 255.f, _b = b / 255.f; float vMin = M_MIN3(r, g, b); float vMax = M_MAX3(r, g, b); float delta = vMax - vMin; if (vMax == vMin) h = 0; else if (_r == vMax) h = (_g - _b) / delta; else if (_g == vMax) h = 2 + (_b - _r) / delta; else if (_b == vMax) h = 4 + (_r - _g) / delta; h = M_MIN(h * 60.f, 36.f); if (h < 0) h += 360.f; l = (vMin + vMax) / 2.0f; if (vMax == vMin) s = 0; else if (l <= 0.5f) s = delta / (vMax + vMin); else s = delta / (2 - vMax - vMin); } inline void hsl2rgb() { float _h = h / 360.f, _s = s / 360.f, _l = l / 360.f; float t1 = 0, t2 = 0, t3 = 0, val = 0; if (_s == 0) { val = _l * 255.f; r = val, g = val, b = val; }else { if (_l < 0.5f) t2 = _l * (1 + _s); else t2 = _l + _s - _l * _s; t1 = 2 * _l - t2; std::function get = std::function([&](int i) { t3 = _h + 1.f / 3.f * -(i - 1); if (t3 < 0) t3++; if (t3 > 1) t3--; if (6.f * t3 < 1) val = t1 + (t2 - t1) * 6.f * t3; else if (2.f * t3 < 1.f) val = t2; else if (3.f * t3 < 2.f) val = t1 + (t2 - t1) * (2.f / 3.f - t3) * 6.f; else val = t1; return val * 255.f; }); r = get(0); g = get(1); b = get(2); } } inline void rgb2hsv() { float rd, gd, bd; float _r = r / 255.f, _g = g / 255.f, _b = b / 255.f; v = M_MAX3(_r, _g, _b); float diff = v - M_MIN3(_r, _g, _b); std::function diffc = std::function([&](float c) { return (v - c) / 6.f / diff + 1.f / 2.f; }); if (diff == 0.f) h = s = 0.f; else { s = diff / v; rd = diffc(_r); gd = diffc(_g); bd = diffc(_b); if (_r == v) h = bd - gd; else if (_g == v) h = (1.f / 3.f) + rd - bd; else if (_b == v) h = (2.f / 3.f) + gd - rd; if (h < 0) h += 1; else if (h > 1) h -= 1; } h *= 360; s *= 100; v *= 100; } inline void hsv2rgb() { float _h = h / 60.f, _s = s / 100.f, _v = v / 100.f; int hi = (int)floor(_h) % 6; uint8_t f = _h - floor(_h); uint8_t p = 255.f * _v * (1.f - _s); uint8_t q = 255.f * _v * (1.f - (_s * f)); uint8_t t = 255.f * _v * (1 - (_s * (1 - f))); _v *= 255.f; switch (hi) { case 0: r = _v; g = t; b = p; break; case 1: r = q; g = _v; b = p; break; case 2: r = p; g = _v; b = t; break; case 3: r = p; g = q; b = _v; break; case 4: r = t; g = p; b = _v; break; case 5: r = _v; g = p; b = q; break; } } #define WARP_HSL(func) rgb2hsl(); func; hsl2rgb(); #define WARP_HSV(func) rgb2hsv(); func; hsv2rgb(); // funcs inline float luminosity() { float lr = ((float)r / 255.0f); lr = lr <= 0.03928f ? lr / 12.92f : powf((lr + 0.055f) / 1.055f, 2.4f); float lg = ((float)g / 255.0f); lg = lg <= 0.03928f ? lg / 12.92f : powf((lg + 0.055f) / 1.055f, 2.4f); float lb = ((float)b / 255.0f); lb = lb <= 0.03928f ? lb / 12.92f : powf((lb + 0.055f) / 1.055f, 2.4f); return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb; } inline float contrast(Color c) { float l1 = luminosity(), l2 = c.luminosity(); return l1 > l2 ? (l1 + 0.05f) / (l2 + 0.05f) : (l2 + 0.05f) / (l1 + 0.05f); } inline int level(Color c) { float cRatio = contrast(c); if (cRatio >= 7.1f) return 3; return (cRatio >= 4.5) ? 2 : 1; } inline bool isDark() { return (float)(r * 299 + g * 587 + b * 114) / 1000.0f < 128.0f; } inline bool isLight() { return !isDark(); } inline Color negate() { return RGB(255-r, 255-g, 255-b); } inline void lighten(float ratio) { WARP_HSL(l += l * ratio) } inline void darken(float ratio) { WARP_HSL(l -= l * ratio) } inline void saturate(float ratio) { WARP_HSL(s += s * ratio) } inline void desaturate(float ratio) { WARP_HSL(s -= s * ratio) } inline Color grayscale() { float v = r * 0.3f + g * 0.59f + b * 0.11f; return RGB(v, v, v); } inline void rorate(float degrees) { WARP_HSL( h = (int)(h + degrees) % 360; h = h < 0 ? 360 + h : h; ) } inline Color mix(Color mixin, float weight) { float w = 2.f * weight - 1; uint8_t _a = a - mixin.a; float w1 = (((w * _a == -1) ? w : (w + _a) / (1.f + w * _a)) + 1.f) / 2.f; float w2 = 1 - w1; return RGBA(w1 * r + w2 * mixin.r, w1 * g + w2 * mixin.g, w1 * b + w2 * mixin.b, a * weight + mixin.a * (1 - weight)); } }; #endif ================================================ FILE: PinBox/PinBox/include/ConfigManager.h ================================================ #pragma once #ifndef _CONFIG_MANAGER_H_ #define _CONFIG_MANAGER_H_ #include <3ds.h> #include "libconfig.h" #include #include #define FORCE_OVERRIDE_VERSION 2 typedef struct ServerConfig { std::string ip; std::string port; std::string name; }; class ConfigManager { private: config_t _config; bool shouldCreateNewConfigFile(); void createNewConfigFile(); void loadConfigFile(); public: ServerConfig* activateServer; std::vector servers; int lastUsingServer = -1; int videoBitRate; int videoGOP; int videoMaxBFrames; int audioBitRate; bool waitForSync; public: static ConfigManager* Get(); ConfigManager(); void InitConfig(); void Save(); void Destroy(); }; #endif ================================================ FILE: PinBox/PinBox/include/HubItem.h ================================================ #ifndef _PP_HUB_TITEM_H_ #define _PP_HUB_TITEM_H_ #include <3ds.h> enum HubItemType { HUB_SCREEN = 0x0, HUB_APP, HUB_MOVIE, }; class HubItem { public: std::string uuid; // app name std::string name; // thumb image should be 64x64 png image u8* thumbBuf; u32 thumbSize; HubItemType type; }; #endif ================================================ FILE: PinBox/PinBox/include/Logger.h ================================================ #ifndef _PP_LOGGER_H_ #define _PP_LOGGER_H_ #include class Logger { public: }; #endif ================================================ FILE: PinBox/PinBox/include/Mutex.h ================================================ #pragma once #include <3ds.h> #include <3ds/svc.h> class Mutex { private: LightLock _handler; bool _isLocked = false; public: Mutex(); ~Mutex(); void Lock(); void TryLock(); void Unlock(); }; ================================================ FILE: PinBox/PinBox/include/PPAudio.h ================================================ #pragma once #ifndef _PP_AUDIO_H_ #define _PP_AUDIO_H_ #include <3ds.h> #include #include "Mutex.h" #define MAX_AUDIO_BUF 2 class PPAudio { private: bool _initialized = false; ndspWaveBuf _waveBuf[MAX_AUDIO_BUF]; int _nextBuf = 0; public: ~PPAudio(); static PPAudio* Get(); void AudioInit(); void AudioExit(); void FillBuffer(u8* buffer, u32 size); }; #endif ================================================ FILE: PinBox/PinBox/include/PPDecoder.h ================================================ #pragma once #include <3ds.h> #include "Mutex.h" #include "yuv_rgb.h" #include <3ds/services/y2r.h> //ffmpeg extern "C" { #include #include #include #include #include #include #include #include #include } #define MEMORY_BUFFER_SIZE 0x1400000 #define MEMORY_BUFFER_PADDING 0x04 typedef struct MemoryBuffer { u8* pBufferAddr; u32 iCursor; u32 iSize; u32 iMaxSize; Mutex* pMutex; void write(u8* buf, u32 size) { if (iSize < size) return; pMutex->Lock(); memcpy(pBufferAddr + iCursor, buf, size); iCursor += size; iSize -= size; pMutex->Unlock(); } int read(u8* buf, u32 size) { if (iCursor == 0) return -1; pMutex->Lock(); int ret = FFMIN(iCursor, size); memcpy(buf, pBufferAddr, ret); iSize += ret; iCursor -= ret; pMutex->Unlock(); return ret; } }MemoryBuffer; typedef struct DecodeState{ Y2RU_ConversionParams y2rParams; Handle endEvent; }DecodeState; class PPDecoder { private: // video stream //AVCodecParserContext* pVideoParser; AVCodecContext* pVideoContext; AVPacket* pVideoPacket; AVFrame* pVideoFrame; DecodeState* pDecodeState; u8* decodeVideoStream(); void initY2RImageConverter(); void convertColor(); // audio stream AVCodecContext* pAudioContext; AVPacket* pAudioPacket; AVFrame* pAudioFrame; public: PPDecoder(); ~PPDecoder(); u32 iFrameWidth; u32 iFrameHeight; void initDecoder(); void releaseDecoder(); u8* appendVideoBuffer(u8* buffer, u32 size); void decodeAudioStream(u8* buffer, u32 size); }; ================================================ FILE: PinBox/PinBox/include/PPGraphics.h ================================================ #pragma once #ifndef _PP_GRAPHICS_H_ #define _PP_GRAPHICS_H_ #include <3ds.h> #include <3ds/gfx.h> #include #include "Color.h" #include //========================================================================================= // Const //========================================================================================= #define CLEAR_COLOR 0x000000FF #define DISPLAY_TRANSFER_FLAGS \ (GX_TRANSFER_FLIP_VERT(0) | GX_TRANSFER_OUT_TILED(0) | GX_TRANSFER_RAW_COPY(0) | \ GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB8) | \ GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) // Used to convert textures to 3DS tiled format // Note: vertical flip flag set so 0,0 is top left of texture #define TEXTURE_TRANSFER_FLAGS \ (GX_TRANSFER_FLIP_VERT(1) | GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_RAW_COPY(0) | \ GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGB8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGB8) | \ GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) #define TEXTURE_RGBA_TRANSFER_FLAGS \ (GX_TRANSFER_FLIP_VERT(1) | GX_TRANSFER_OUT_TILED(1) | GX_TRANSFER_RAW_COPY(0) | \ GX_TRANSFER_IN_FORMAT(GX_TRANSFER_FMT_RGBA8) | GX_TRANSFER_OUT_FORMAT(GX_TRANSFER_FMT_RGBA8) | \ GX_TRANSFER_SCALING(GX_TRANSFER_SCALE_NO)) #define TEX_GRAPHIC 0 #define TEX_VIDEO_STREAM_LEFT 1 #define TEX_VIDEO_STREAM_RIGHT 2 #define TEX_FONT_GRAPHIC 3 //========================================================================================= // Type //========================================================================================= typedef struct { float x; float y; }Vector2; typedef struct { float x; float y; float z; }Vector3; typedef struct { Vector3 position; u32 color; }VertexPosCol; typedef struct { Vector3 position; Vector2 textcoord; }VertexPosTex; typedef struct { C3D_Tex tex; u32 width; u32 height; bool initialized = false; }Sprite; //========================================================================================= // Class //========================================================================================= class PPGraphics { public: Color PrimaryColor = Color{ 76, 175, 80, 255 }; Color PrimaryDarkColor = Color{ 0, 150, 136, 255 }; Color AccentColor = Color{ 230, 126, 34, 255 }; Color AccentDarkColor = Color{ 211, 84, 0, 255 }; Color PrimaryTextColor = Color{ 38, 50, 56, 255 }; Color AccentTextColor = Color{ 255, 255, 255, 255 }; Color TransBackgroundDark = Color{3, 3, 3, 180}; private: C3D_RenderTarget* mRenderTargetTop = nullptr; C3D_Mtx mProjectionTop; C3D_RenderTarget* mRenderTargetBtm = nullptr; C3D_Mtx mProjectionBtm; DVLB_s* mVShaderDVLB; shaderProgram_s mShaderProgram; int mULocProjection; // system font C3D_Tex* mGlyphSheets; // top screen sprite Sprite* mTopScreenSprite; // Temporary memory pool void *memoryPoolAddr = NULL; u32 memoryPoolIndex = 0; u32 memoryPoolSize = 0; gfxScreen_t mCurrentDrawScreen = GFX_TOP; int mRendering = 0; // Texture cache std::map mTexCached; void setupForPosCollEnv(void* vertices); void setupForPosTexlEnv(void* vertices, u32 color, int texID); int getTextUnit(GPU_TEXUNIT unit); void *allocMemoryPoolAligned(u32 size, u32 alignment); void resetMemoryPool() { memoryPoolIndex = 0; } public: ~PPGraphics(); static PPGraphics* Get(); void GraphicsInit(); void GraphicExit(); // cache functions Sprite* AddCacheImageAsset(const char* name, std::string key); Sprite* AddCacheImage(const char* path, std::string key); Sprite* AddCacheImage(u8 *buf, u32 size, std::string key); Sprite* GetCacheImage(std::string key); // draw functions void BeginRender(); void RenderOn(gfxScreen_t screen); void EndRender(); void UpdateTopScreenSprite(u8* data, u32 size); void DrawTopScreenSprite(); // Draw image void DrawImage(Sprite* sprite, int x, int y); void DrawImage(std::string key, int x, int y) { DrawImage(GetCacheImage(key), x, y); } void DrawImage(Sprite* sprite, int x, int y, int w, int h); void DrawImage(std::string key, int x, int y, int w, int h) { DrawImage(GetCacheImage(key), x, y, w, h); } void DrawImage(Sprite* sprite, int x, int y, int w, int h, int degrees); void DrawImage(std::string key, int x, int y, int w, int h, int degrees) { DrawImage(GetCacheImage(key), x, y, w, h, degrees); } void DrawImage(Sprite* sprite, int x, int y, int w, int h, int degrees, Vector2 anchor); void DrawImage(std::string key, int x, int y, int w, int h, int degrees, Vector2 anchor) { DrawImage(GetCacheImage(key), x, y, w, h, degrees, anchor); } // draw rectangle void DrawRectangle(float x, float y, float w, float h, Color color, float rounding = 0.0f); // mask void StartMasked(float x, float y, float w, float h, gfxScreen_t screen) const; void StopMasked() const; // draw text void DrawText(const char* text, float x, float y, float scaleX, float scaleY, Color color, bool baseline); void DrawTextAutoWrap(const char* text, float x, float y, float w, float scaleX, float scaleY, Color color, bool baseline); Vector2 GetTextSize(const char* text, float scaleX, float scaleY); Vector3 GetTextSizeAutoWrap(const char* text, float scaleX, float scaleY, float w); }; #endif ================================================ FILE: PinBox/PinBox/include/PPMessage.h ================================================ #pragma once #ifndef _PP_MESSAGE_H_ #define _PP_MESSAGE_H_ #include <3ds.h> #include #include #include #include #define WRITE_CHAR_PTR(BUFFER, DATA, SIZE) memcpy(BUFFER, DATA, SIZE); BUFFER += SIZE; #define WRITE_U8(BUFFER, DATA) *(BUFFER++) = DATA & 0xff; #define WRITE_U16(BUFFER, DATA) *(BUFFER++) = DATA & 0xff; *(BUFFER++) = (DATA >> 8) & 0xff; #define WRITE_U32(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; *(BUFFER++) = DATA >> 16; *(BUFFER++) = DATA >> 24; #define READ_U8(BUFFER, INDEX) BUFFER[INDEX]; #define READ_U16(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8; #define READ_U32(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8 | BUFFER[INDEX + 2] << 16 | BUFFER[INDEX + 3] << 24; #define IS_INVALID_CODE(BUFFER, INDEX) BUFFER[INDEX] != 'P' || BUFFER[INDEX+1] != 'P' || BUFFER[INDEX+2] != 'B' || BUFFER[INDEX+3] != 'X' class PPMessage { private: //----------------------------------------------- // message header - 9 bytes // [4b] validate code : "PPBX" // [1b] message code : 0 to 255 - define message type // [4b] message content size //----------------------------------------------- const char g_validateCode[4] = { 'P','P','B','X' }; u8 g_code = 0; u32 g_contentSize = 0; //----------------------------------------------- // message content //----------------------------------------------- u8* g_content = nullptr; public: ~PPMessage(); u32 GetMessageSize() const { return g_contentSize + 9; } u8* GetMessageContent() { return g_content; } u32 GetContentSize() { return g_contentSize; } u8 GetMessageCode() { return g_code; } //----------------------------------------------- // NOTE: after using this message, returned data must be free whenever it sent. //----------------------------------------------- u8* BuildMessage(u8* contentBuffer, u32 contentSize); u8* BuildMessageEmpty(); void BuildMessageHeader(u8 code); bool ParseHeader(u8* buffer); void ClearHeader(); }; #endif ================================================ FILE: PinBox/PinBox/include/PPSession.h ================================================ #pragma once #ifndef _PP_SESSION_H_ #define _PP_SESSION_H_ //======================================================================= // PinBox Video Session // container streaming data can be movie or screen capture // With: // 1, Movie : // TODO: using ffmpeg to decode movie stream from server // TODO: support 3D movie on N3DS // TODO: mainly support RGB565 for lower size and speed up stream // 2, Screen Capture: // TODO: capture entire screen or a part of screen that config in server //----------------------------------------------------------------------- // Note: each session is running standalone and only 1 session can be run // at a time. //======================================================================= #include <3ds.h> #include #include #include #include #include #include #include #include #include #include #include #include #include #include "Mutex.h" #include "PPMessage.h" #include "HubItem.h" enum PPSession_Type { PPSESSION_NONE, PPSESSION_MOVIE, PPSESSION_SCREEN_CAPTURE, PPSESSION_INPUT_CAPTURE}; #define MSG_COMMAND_SIZE 9 #define PPREQUEST_AUTHEN 50 #define PPREQUEST_HEADER 10 #define PPREQUEST_BODY 15 // authentication code #define MSG_CODE_REQUEST_AUTHENTICATION_SESSION 1 #define MSG_CODE_RESULT_AUTHENTICATION_SUCCESS 5 #define MSG_CODE_RESULT_AUTHENTICATION_FAILED 6 // screen capture code #define MSG_CODE_REQUEST_START_SCREEN_CAPTURE 10 #define MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE 11 #define MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE 12 #define MSG_CODE_REQUEST_NEW_SCREEN_FRAME 15 #define MSG_CODE_REQUEST_SCREEN_RECEIVED_FRAME 16 #define MSG_CODE_REQUEST_NEW_AUDIO_FRAME 18 #define MSG_CODE_REQUEST_RECEIVED_AUDIO_FRAME 19 // input #define MSG_CODE_SEND_INPUT_CAPTURE 42 #define MSG_CODE_SEND_INPUT_CAPTURE_IDLE 44 // hub #define MSG_CODE_REQUEST_HUB_ITEMS 60 #define MSG_CODE_RECEIVED_HUB_ITEMS 61 // audio #define AUDIO_CHANNEL 0x08 typedef struct { void *msgBuffer; u32 msgSize; } QueueMessage; class PPSessionManager; enum ppConectState { IDLE, CONNECTING, CONNECTED, FAIL }; typedef std::function PPNetworkReceivedRequest; typedef std::function PPNetworkCallback; class PPSession { private: PPSessionManager *_manager; PPMessage* _tmpMessage = nullptr; bool _authenticated = false; std::queue _sendingMessages; Mutex* _queueMessageMutex; private: // threading bool _running = false; bool _kill = false; Thread _thread; // socket const char* _ip = 0; const char* _port = 0; int _sock = -1; ppConectState _connect_state = IDLE; // test connection result int volatile _testConnectionResult = 0; // hub items std::vector _hubItems; void connectToServer(); void closeConnect(); void recvSocketData(); void sendMessageData(); void processReceivedMsg(u8* buffer, u32 size, u32 tag);; void processMessageData(u8* buffer, size_t size); public: PPSession(); ~PPSession(); int GetTestConnectionResult() const { return _testConnectionResult; } void InitTestSession(PPSessionManager* manager, const char* ip, const char* port); void threadTest(); void InitSession(PPSessionManager* manager, const char* ip, const char* port); void threadMain(); void ReleaseSession(); void CleanUp(); void StartStream(); void StopStream(); void RequestForData(u32 size, u32 tag = 0); void AddMessageToQueue(u8 *msgBuffer, int32_t msgSize); int GetHubItemCount() { return _hubItems.size(); } HubItem* GetHubItem(int i) { return _hubItems.at(i); } private: bool isInputStarted = false; bool isSessionStarted = false; public: // Authentication void SendMsgAuthentication(); // Stream void SendMsgStartStream(); void SendMsgStopStream(); // Setting void SendMsgChangeSetting(); // Hub void SendMsgRequestHubItems(); // Input bool SendMsgSendInputData(u32 down, u32 up, short cx, short cy, short ctx, short cty); }; #endif ================================================ FILE: PinBox/PinBox/include/PPSessionManager.h ================================================ #pragma once #include #include "PPSession.h" #include #include #include "opusfile.h" #include #include #include "PPDecoder.h" #include "constant.h" #include "ConfigManager.h" enum SessionState { SS_NOT_CONNECTED = 0, SS_CONNECTING, SS_CONNECTED, SS_PAIRED, SS_STREAMING, SS_FAILED }; typedef struct { u8 *buffer; u32 size; } VideoFrame; enum BusyState { BS_NONE = 0, BS_AUTHENTICATION, BS_HUB_ITEMS }; class PPSessionManager { protected: PPSession* _session = nullptr; PPSession* _testSession = nullptr; //-------------------------------------------- // decoder //-------------------------------------------- PPDecoder* _decoder = nullptr; //-------------------------------------------- // input //-------------------------------------------- u32 _oldDown; u32 _oldUp; short _oldCX; short _oldCY; short _oldCTX; short _oldCTY; bool _initInputFirstFrame = false; //-------------------------------------------- // fps //-------------------------------------------- u64 _lastRenderTime = 0; float _currentRenderFPS = 0.0f; u32 _renderFrames = 0; u64 _lastVideoTime = 0; float _currentVideoFPS = 0.0f; u32 _videoFrame = 0; bool _receivedFirstVideoFrame = false; SessionState _sessionState = SS_NOT_CONNECTED; BusyState _busyState = BS_NONE; public: PPSessionManager(); ~PPSessionManager(); /** * \brief Test connections * \param config server informations * \return 0 as pending\n * -1 as failed\n * 1 as successfully */ int TestConnection(ServerConfig *config); /** * \brief Must call after @ref InitNewSession to connect to server by config. * update follow @ref GetSessionState to get connection state * @ref GetSessionState return @ref SS_FAILED if connect error * return @ref SS_PAIRED if connect and authentication successfully * \param config server informations * \return @ref SessionState */ SessionState ConnectToServer(ServerConfig* config); /** * \brief Disconnect to Paired server * @ref GetSessionState will return @ref SS_NOT_CONNECTED */ void DisconnectToServer(); int GetHubItemCount() { return _session->GetHubItemCount(); } HubItem* GetHubItem(int i) { return _session->GetHubItem(i); } /** * \brief Get current session state * \return @ref SessionState */ SessionState GetSessionState() const { return _sessionState; }; /** * \brief Set current session state * \param v new state that apply for session */ void SetSessionState(SessionState v) { _sessionState = v; }; /** * \brief init video and audio decoder */ void InitDecoder(); /** * \brief release video and audio decoder */ void ReleaseDecoder(); /** * \brief update new stream setting to server * user need update config from @ref PPConfigManager first before call this function */ void UpdateStreamSetting(); /** * \brief get server's controller profiles ( it only return key name of each profiles ) */ void GetControllerProfiles(); /** * \brief Send authentication message */ void Authentication(); BusyState GetBusyState() { return _busyState; } void SetBusyState(BusyState bs) { _busyState = bs; } /** * \brief Tell server that client want to start streaming * */ void StartStreaming(); void StopStreaming(); void StartFPSCounter(); void UpdateFPSCounter(); void UpdateInputStream(u32 down, u32 up, short cx, short cy, short ctx, short cty); void ProcessVideoFrame(u8* buffer, u32 size); void ProcessAudioFrame(u8* buffer, u32 size); void DrawVideoFrame(); // fps float GetFPS() const { return _currentRenderFPS; } float GetVideoFPS() const { return _currentVideoFPS; } }; ================================================ FILE: PinBox/PinBox/include/PPUI.h ================================================ #pragma once #ifndef _PP_UI_H_ #define _PP_UI_H_ #include <3ds.h> #include #include #include "PPGraphics.h" #include "PPSessionManager.h" #include "easing.h" #include "Color.h" //#define UI_DEBUG 1 #define RET_CLOSE_APP -1000 #define SCROLL_THRESHOLD 5 #define SCROLL_BAR_MIN 0.2f #define SCROLL_SPEED_MODIFIED 0.2f #define SCROLL_SPEED_STEP 0.18f enum Direction { D_NONE = 0, D_HORIZONTAL = 1, D_VERTICAL = 2, D_BOTH = 3 }; typedef struct DialogBoxOverride { bool isActivate = false; Color TitleBgColor; Color TitleTextColor; const char* Title = nullptr; const char* Body = nullptr; }; typedef struct WH { int width; int height; }; typedef std::function TabContentDraw; typedef std::function PopupCallback; typedef std::function WHCallback; typedef std::function ResultCallback; class PPUI { public: static u32 getKeyDown(); static u32 getKeyHold(); static u32 getKeyUp(); static circlePosition getLeftCircle(); static circlePosition getRightCircle(); static u32 getSleepModeState(); static void UpdateInput(); static bool TouchDownOnArea(float x, float y, float w, float h); static bool TouchUpOnArea(float x, float y, float w, float h); static bool TouchDown(); static bool TouchMove(); static bool TouchUp(); // RESOURCES static void InitResource(); static void CleanupResource(); // SCREEN static int DrawIdleTopScreen(PPSessionManager *sessionManager); static int DrawBtmServerSelectScreen(PPSessionManager *sessionManager); static int DrawBtmAddNewServerProfileScreen(PPSessionManager *sessionManager, ResultCallback cancel, ResultCallback ok); static int DrawBtmPairedScreen(PPSessionManager *sessionManager); static int DrawStreamConfigUI(PPSessionManager *sessionManager, ResultCallback cancel, ResultCallback ok); static int DrawIdleBottomScreen(PPSessionManager *sessionManager); static void InfoBox(PPSessionManager *sessionManager); // TAB static int DrawTabs(const char* tabs[], u32 tabCount, int activeTab, float x, float y, float w, float h); // DIALOG static void OverrideDialogTypeWarning(); static void OverrideDialogTypeInfo(); static void OverrideDialogTypeSuccess(); static void OverrideDialogTypeCritical(); static void OverrideDialogContent(const char* title, const char* body); static int DrawDialogKeyboard( ResultCallback cancelCallback, ResultCallback okCallback); static int DrawDialogNumberInput( ResultCallback cancelCallback, ResultCallback okCallback); static int DrawDialogLoading(const char* title, const char* body, PopupCallback callback); static int DrawDialogMessage(PPSessionManager *sessionManager, const char* title, const char* body); static int DrawDialogMessage(PPSessionManager *sessionManager, const char* title, const char* body, PopupCallback closeCallback); static int DrawDialogMessage(PPSessionManager *sessionManager, const char* title, const char* body, PopupCallback cancelCallback, PopupCallback okCallback); static int DrawDialogBox(PPSessionManager *sessionManager); // SCROLL BOX static Vector2 ScrollBox(float x, float y, float w, float h, Direction dir, Vector2 cursor, WHCallback contentDraw); // SLIDE static float Slide(float x, float y, float w, float h, float val, float min, float max, float step, const char* label); // CHECKBOX static bool ToggleBox(float x, float y, float w, float h, bool value, const char* label); // SELECT BOX static bool SelectBox(float x, float y, float w, float h, Color color, float rounding); // BUTTON static bool FlatButton(float x, float y, float w, float h, const char* label, float rounding = 0.0f); static bool FlatDarkButton(float x, float y, float w, float h, const char* label, float rounding = 0.0f); static bool FlatColorButton(float x, float y, float w, float h, const char* label, Color colNormal, Color colActive, Color txtCol, float rounding = 0.0f); static bool RepeatButton(float x, float y, float w, float h, const char* label, Color colNormal, Color colActive, Color txtCol); // TEXT static int LabelBox(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale = 0.5f, float rounding = 0.f); static int LabelBoxAutoWrap(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale = 0.5f, float rounding = 0.f); static int LabelBoxLeft(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale = 0.5f, float rounding = 0.f); // POPUP static bool HasPopup(); static PopupCallback GetPopup(); static void ClosePopup(); static void AddPopup(PopupCallback callback); }; #endif ================================================ FILE: PinBox/PinBox/include/constant.h ================================================ #pragma once #define SOC_ALIGN 0x1000 #define SOC_BUFFERSIZE 0x100000 #define CONSOLE_DEBUG 1 #define USE_CITRA 1 ================================================ FILE: PinBox/PinBox/include/easing.h ================================================ #pragma once enum easing_functions { EaseInSine, EaseOutSine, EaseInOutSine, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc, EaseInBack, EaseOutBack, EaseInOutBack, EaseInElastic, EaseOutElastic, EaseInOutElastic, EaseInBounce, EaseOutBounce, EaseInOutBounce }; typedef double(*easingFunction)(double); easingFunction getEasingFunction( easing_functions function ); ================================================ FILE: PinBox/PinBox/include/lodepng.h ================================================ /* LodePNG version 20180819 Copyright (c) 2005-2018 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef LODEPNG_H #define LODEPNG_H #include /*for size_t*/ extern const char* LODEPNG_VERSION_STRING; /* The following #defines are used to create code sections. They can be disabled to disable code sections, which can give faster compile time and smaller binary. The "NO_COMPILE" defines are designed to be used to pass as defines to the compiler command to disable them without modifying this header, e.g. -DLODEPNG_NO_COMPILE_ZLIB for gcc. In addition to those below, you can also define LODEPNG_NO_COMPILE_CRC to allow implementing a custom lodepng_crc32. */ /*deflate & zlib. If disabled, you must specify alternative zlib functions in the custom_zlib field of the compress and decompress settings*/ #ifndef LODEPNG_NO_COMPILE_ZLIB #define LODEPNG_COMPILE_ZLIB #endif /*png encoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_PNG #define LODEPNG_COMPILE_PNG #endif /*deflate&zlib decoder and png decoder*/ #ifndef LODEPNG_NO_COMPILE_DECODER #define LODEPNG_COMPILE_DECODER #endif /*deflate&zlib encoder and png encoder*/ #ifndef LODEPNG_NO_COMPILE_ENCODER #define LODEPNG_COMPILE_ENCODER #endif /*the optional built in harddisk file loading and saving functions*/ #ifndef LODEPNG_NO_COMPILE_DISK #define LODEPNG_COMPILE_DISK #endif /*support for chunks other than IHDR, IDAT, PLTE, tRNS, IEND: ancillary and unknown chunks*/ #ifndef LODEPNG_NO_COMPILE_ANCILLARY_CHUNKS #define LODEPNG_COMPILE_ANCILLARY_CHUNKS #endif /*ability to convert error numerical codes to English text string*/ #ifndef LODEPNG_NO_COMPILE_ERROR_TEXT #define LODEPNG_COMPILE_ERROR_TEXT #endif /*Compile the default allocators (C's free, malloc and realloc). If you disable this, you can define the functions lodepng_free, lodepng_malloc and lodepng_realloc in your source files with custom allocators.*/ #ifndef LODEPNG_NO_COMPILE_ALLOCATORS #define LODEPNG_COMPILE_ALLOCATORS #endif /*compile the C++ version (you can disable the C++ wrapper here even when compiling for C++)*/ #ifdef __cplusplus #ifndef LODEPNG_NO_COMPILE_CPP #define LODEPNG_COMPILE_CPP #endif #endif #ifdef LODEPNG_COMPILE_CPP #include #include #endif /*LODEPNG_COMPILE_CPP*/ #ifdef LODEPNG_COMPILE_PNG /*The PNG color types (also used for raw).*/ typedef enum LodePNGColorType { LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ LCT_RGB = 2, /*RGB: 8,16 bit*/ LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ LCT_GREY_ALPHA = 4, /*greyscale with alpha: 8,16 bit*/ LCT_RGBA = 6 /*RGB with alpha: 8,16 bit*/ } LodePNGColorType; #ifdef LODEPNG_COMPILE_DECODER /* Converts PNG data in memory to raw pixel data. out: Output parameter. Pointer to buffer that will contain the raw pixel data. After decoding, its size is w * h * (bytes per pixel) bytes larger than initially. Bytes per pixel depends on colortype and bitdepth. Must be freed after usage with free(*out). Note: for 16-bit per channel colors, uses big endian format like PNG does. w: Output parameter. Pointer to width of pixel data. h: Output parameter. Pointer to height of pixel data. in: Memory buffer with the PNG file. insize: size of the in buffer. colortype: the desired color type for the raw output image. See explanation on PNG color types. bitdepth: the desired bit depth for the raw output image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_memory, but always decodes to 32-bit RGBA raw image*/ unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); /*Same as lodepng_decode_memory, but always decodes to 24-bit RGB raw image*/ unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize); #ifdef LODEPNG_COMPILE_DISK /* Load PNG from disk, from file with given name. Same as the other decode functions, but instead takes a filename as input. */ unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_decode_file, but always decodes to 32-bit RGBA raw image.*/ unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); /*Same as lodepng_decode_file, but always decodes to 24-bit RGB raw image.*/ unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Converts raw pixel data into a PNG image in memory. The colortype and bitdepth of the output PNG image cannot be chosen, they are automatically determined by the colortype, bitdepth and content of the input pixel data. Note: for 16-bit per channel colors, needs big endian format like PNG does. out: Output parameter. Pointer to buffer that will contain the PNG image data. Must be freed after usage with free(*out). outsize: Output parameter. Pointer to the size in bytes of the out buffer. image: The raw pixel data to encode. The size of this buffer should be w * h * (bytes per pixel), bytes per pixel depends on colortype and bitdepth. w: width of the raw pixel data in pixels. h: height of the raw pixel data in pixels. colortype: the color type of the raw input image. See explanation on PNG color types. bitdepth: the bit depth of the raw input image. See explanation on PNG color types. Return value: LodePNG error code (0 means no error). */ unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_memory, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_memory, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DISK /* Converts raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth); /*Same as lodepng_encode_file, but always encodes from 32-bit RGBA raw image.*/ unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); /*Same as lodepng_encode_file, but always encodes from 24-bit RGB raw image.*/ unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h); #endif /*LODEPNG_COMPILE_DISK*/ #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_CPP namespace lodepng { #ifdef LODEPNG_COMPILE_DECODER /*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, size_t insize, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::vector& in, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts PNG file from disk to raw pixel data in memory. Same as the other decode functions, but instead takes a filename as input. */ unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /*Same as lodepng_encode_memory, but encodes to an std::vector. colortype is that of the raw input data. The output PNG color type will be auto chosen.*/ unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #ifdef LODEPNG_COMPILE_DISK /* Converts 32-bit RGBA raw pixel data into a PNG file on disk. Same as the other encode functions, but instead takes a filename as output. NOTE: This overwrites existing files without warning! */ unsigned encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); unsigned encode(const std::string& filename, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype = LCT_RGBA, unsigned bitdepth = 8); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_ENCODER */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ERROR_TEXT /*Returns an English description of the numerical error code.*/ const char* lodepng_error_text(unsigned code); #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ #ifdef LODEPNG_COMPILE_DECODER /*Settings for zlib decompression*/ typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; struct LodePNGDecompressSettings { /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ /*use custom zlib decoder instead of built in one (default: null)*/ unsigned(*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); /*use custom deflate decoder instead of built in one (default: null) if custom_zlib is used, custom_deflate is ignored since only the built in zlib function will call custom_deflate*/ unsigned(*custom_inflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGDecompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGDecompressSettings lodepng_default_decompress_settings; void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Settings for zlib compression. Tweaking these settings tweaks the balance between speed and compression ratio. */ typedef struct LodePNGCompressSettings LodePNGCompressSettings; struct LodePNGCompressSettings /*deflate = compress*/ { /*LZ77 related settings*/ unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ unsigned windowsize; /*must be a power of two <= 32768. higher compresses more but is slower. Default value: 2048.*/ unsigned minmatch; /*mininum lz77 length. 3 is normally best, 6 can be better for some PNGs. Default: 0*/ unsigned nicematch; /*stop searching if >= this length found. Set to 258 for best compression. Default: 128*/ unsigned lazymatching; /*use lazy matching: better compression but a bit slower. Default: true*/ /*use custom zlib encoder instead of built in one (default: null)*/ unsigned(*custom_zlib)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); /*use custom deflate encoder instead of built in one (default: null) if custom_zlib is used, custom_deflate is ignored since only the built in zlib function will call custom_deflate*/ unsigned(*custom_deflate)(unsigned char**, size_t*, const unsigned char*, size_t, const LodePNGCompressSettings*); const void* custom_context; /*optional custom settings for custom functions*/ }; extern const LodePNGCompressSettings lodepng_default_compress_settings; void lodepng_compress_settings_init(LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_PNG /* Color mode of an image. Contains all information required to decode the pixel bits to RGBA colors. This information is the same as used in the PNG file format, and is used both for PNG and raw image data in LodePNG. */ typedef struct LodePNGColorMode { /*header (IHDR)*/ LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ /* palette (PLTE and tRNS) Dynamically allocated with the colors of the palette, including alpha. When encoding a PNG, to store your colors in the palette of the LodePNGColorMode, first use lodepng_palette_clear, then for each color use lodepng_palette_add. If you encode an image without alpha with palette, don't forget to put value 255 in each A byte of the palette. When decoding, by default you can ignore this palette, since LodePNG already fills the palette colors in the pixels of the raw RGBA output. The palette is only supported for color type 3. */ unsigned char* palette; /*palette in RGBARGBA... order. When allocated, must be either 0, or have size 1024*/ size_t palettesize; /*palette size in number of colors (amount of bytes is 4 * palettesize)*/ /* transparent color key (tRNS) This color uses the same bit depth as the bitdepth value in this struct, which can be 1-bit to 16-bit. For greyscale PNGs, r, g and b will all 3 be set to the same. When decoding, by default you can ignore this information, since LodePNG sets pixels with this key to transparent already in the raw RGBA output. The color key is only supported for color types 0 and 2. */ unsigned key_defined; /*is a transparent color key given? 0 = false, 1 = true*/ unsigned key_r; /*red/greyscale component of color key*/ unsigned key_g; /*green component of color key*/ unsigned key_b; /*blue component of color key*/ } LodePNGColorMode; /*init, cleanup and copy functions to use with this struct*/ void lodepng_color_mode_init(LodePNGColorMode* info); void lodepng_color_mode_cleanup(LodePNGColorMode* info); /*return value is error code (0 means no error)*/ unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source); void lodepng_palette_clear(LodePNGColorMode* info); /*add 1 color to the palette*/ unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a); /*get the total amount of bits per pixel, based on colortype and bitdepth in the struct*/ unsigned lodepng_get_bpp(const LodePNGColorMode* info); /*get the amount of color channels used, based on colortype in the struct. If a palette is used, it counts as 1 channel.*/ unsigned lodepng_get_channels(const LodePNGColorMode* info); /*is it a greyscale type? (only colortype 0 or 4)*/ unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info); /*has it got an alpha channel? (only colortype 2 or 6)*/ unsigned lodepng_is_alpha_type(const LodePNGColorMode* info); /*has it got a palette? (only colortype 3)*/ unsigned lodepng_is_palette_type(const LodePNGColorMode* info); /*only returns true if there is a palette and there is a value in the palette with alpha < 255. Loops through the palette to check this.*/ unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info); /* Check if the given color info indicates the possibility of having non-opaque pixels in the PNG image. Returns true if the image can have translucent or invisible pixels (it still be opaque if it doesn't use such pixels). Returns false if the image can only have opaque pixels. In detail, it returns true only if it's a color type with alpha, or has a palette with non-opaque values, or if "key_defined" is true. */ unsigned lodepng_can_have_alpha(const LodePNGColorMode* info); /*Returns the byte size of a raw image buffer with given width, height and color mode*/ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*The information of a Time chunk in PNG.*/ typedef struct LodePNGTime { unsigned year; /*2 bytes used (0-65535)*/ unsigned month; /*1-12*/ unsigned day; /*1-31*/ unsigned hour; /*0-23*/ unsigned minute; /*0-59*/ unsigned second; /*0-60 (to allow for leap seconds)*/ } LodePNGTime; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Information about the PNG image, except pixels, width and height.*/ typedef struct LodePNGInfo { /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned filter_method; /*filter method of the original file*/ unsigned interlace_method; /*interlace method of the original file: 0=none, 1=Adam7*/ LodePNGColorMode color; /*color type and bits, palette and transparency of the PNG file*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /* Suggested background color chunk (bKGD) This uses the same color mode and bit depth as the PNG (except no alpha channel), with values truncated to the bit depth in the unsigned integer. For greyscale and palette PNGs, the value is stored in background_r. The values in background_g and background_b are then unused. So when decoding, you may get these in a different color mode than the one you requested for the raw pixels. When encoding with auto_convert, you must use the color model defined in info_png.color for these values. The encoder normally ignores info_png.color when auto_convert is on, but will use it to interpret these values (and convert copies of them to its chosen color model). When encoding, avoid setting this to an expensive color, such as a non-grey value when the image is grey, or the compression will be worse since it will be forced to write the PNG with a more expensive color mode (when auto_convert is on). The decoder does not use this background color to edit the color of pixels. This is a completely optional metadata feature. */ unsigned background_defined; /*is a suggested background color given?*/ unsigned background_r; /*red/grey/palette component of suggested background color*/ unsigned background_g; /*green component of suggested background color*/ unsigned background_b; /*blue component of suggested background color*/ /* non-international text chunks (tEXt and zTXt) The char** arrays each contain num strings. The actual messages are in text_strings, while text_keys are keywords that give a short description what the actual text represents, e.g. Title, Author, Description, or anything else. All the string fields below including keys, names and language tags are null terminated. The PNG specification uses null characters for the keys, names and tags, and forbids null characters to appear in the main text which is why we can use null termination everywhere here. A keyword is minimum 1 character and maximum 79 characters long. It's discouraged to use a single line length longer than 79 characters for texts. Don't allocate these text buffers yourself. Use the init/cleanup functions correctly and use lodepng_add_text and lodepng_clear_text. */ size_t text_num; /*the amount of texts in these char** buffers (there may be more texts in itext)*/ char** text_keys; /*the keyword of a text chunk (e.g. "Comment")*/ char** text_strings; /*the actual text*/ /* international text chunks (iTXt) Similar to the non-international text chunks, but with additional strings "langtags" and "transkeys". */ size_t itext_num; /*the amount of international texts in this PNG*/ char** itext_keys; /*the English keyword of the text chunk (e.g. "Comment")*/ char** itext_langtags; /*language tag for this text's language, ISO/IEC 646 string, e.g. ISO 639 language tag*/ char** itext_transkeys; /*keyword translated to the international language - UTF-8 string*/ char** itext_strings; /*the actual international text - UTF-8 string*/ /*time chunk (tIME)*/ unsigned time_defined; /*set to 1 to make the encoder generate a tIME chunk*/ LodePNGTime time; /*phys chunk (pHYs)*/ unsigned phys_defined; /*if 0, there is no pHYs chunk and the values below are undefined, if 1 else there is one*/ unsigned phys_x; /*pixels per unit in x direction*/ unsigned phys_y; /*pixels per unit in y direction*/ unsigned phys_unit; /*may be 0 (unknown unit) or 1 (metre)*/ /* Color profile related chunks: gAMA, cHRM, sRGB, iCPP LodePNG does not apply any color conversions on pixels in the encoder or decoder and does not interpret these color profile values. It merely passes on the information. If you wish to use color profiles and convert colors, please use these values with a color management library. See the PNG, ICC and sRGB specifications for more information about the meaning of these values. */ /* gAMA chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned gama_defined; /* Whether a gAMA chunk is present (0 = not present, 1 = present). */ unsigned gama_gamma; /* Gamma exponent times 100000 */ /* cHRM chunk: optional, overridden by sRGB or iCCP if those are present. */ unsigned chrm_defined; /* Whether a cHRM chunk is present (0 = not present, 1 = present). */ unsigned chrm_white_x; /* White Point x times 100000 */ unsigned chrm_white_y; /* White Point y times 100000 */ unsigned chrm_red_x; /* Red x times 100000 */ unsigned chrm_red_y; /* Red y times 100000 */ unsigned chrm_green_x; /* Green x times 100000 */ unsigned chrm_green_y; /* Green y times 100000 */ unsigned chrm_blue_x; /* Blue x times 100000 */ unsigned chrm_blue_y; /* Blue y times 100000 */ /* sRGB chunk: optional. May not appear at the same time as iCCP. If gAMA is also present gAMA must contain value 45455. If cHRM is also present cHRM must contain respectively 31270,32900,64000,33000,30000,60000,15000,6000. */ unsigned srgb_defined; /* Whether an sRGB chunk is present (0 = not present, 1 = present). */ unsigned srgb_intent; /* Rendering intent: 0=perceptual, 1=rel. colorimetric, 2=saturation, 3=abs. colorimetric */ /* iCCP chunk: optional. May not appear at the same time as sRGB. LodePNG does not parse or use the ICC profile (except its color space header field for an edge case), a separate library to handle the ICC data (not included in LodePNG) format is needed to use it for color management and conversions. For encoding, if iCCP is present, gAMA and cHRM are recommended to be added as well with values that match the ICC profile as closely as possible, if you wish to do this you should provide the correct values for gAMA and cHRM and enable their '_defined' flags since LodePNG will not automatically compute them from the ICC profile. For encoding, the ICC profile is required by the PNG specification to be an "RGB" profile for non-grey PNG color types and a "GRAY" profile for grey PNG color types. If you disable auto_convert, you must ensure the ICC profile type matches your requested color type, else the encoder gives an error. If auto_convert is enabled (the default), and the ICC profile is not a good match for the pixel data, this will result in an encoder error if the pixel data has non-grey pixels for a GRAY profile, or a silent less-optimal compression of the pixel data if the pixels could be encoded as greyscale but the ICC profile is RGB. To avoid this do not set an ICC profile in the image unless there is a good reason for it, and when doing so make sure you compute it carefully to avoid the above problems. */ unsigned iccp_defined; /* Whether an iCCP chunk is present (0 = not present, 1 = present). */ char* iccp_name; /* Null terminated string with profile name, 1-79 bytes */ /* The ICC profile in iccp_profile_size bytes. Don't allocate this buffer yourself. Use the init/cleanup functions correctly and use lodepng_set_icc and lodepng_clear_icc. */ unsigned char* iccp_profile; unsigned iccp_profile_size; /* The size of iccp_profile in bytes */ /* End of color profile related chunks */ /* unknown chunks: chunks not known by LodePNG, passed on byte for byte. There are 3 buffers, one for each position in the PNG where unknown chunks can appear. Each buffer contains all unknown chunks for that position consecutively. The 3 positions are: 0: between IHDR and PLTE, 1: between PLTE and IDAT, 2: between IDAT and IEND. For encoding, do not store critical chunks or known chunks that are enabled with a "_defined" flag above in here, since the encoder will blindly follow this and could then encode an invalid PNG file (such as one with two IHDR chunks or the disallowed combination of sRGB with iCCP). But do use this if you wish to store an ancillary chunk that is not supported by LodePNG (such as sPLT or hIST), or any non-standard PNG chunk. Do not allocate or traverse this data yourself. Use the chunk traversing functions declared later, such as lodepng_chunk_next and lodepng_chunk_append, to read/write this struct. */ unsigned char* unknown_chunks_data[3]; size_t unknown_chunks_size[3]; /*size in bytes of the unknown chunks, given for protection*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGInfo; /*init, cleanup and copy functions to use with this struct*/ void lodepng_info_init(LodePNGInfo* info); void lodepng_info_cleanup(LodePNGInfo* info); /*return value is error code (0 means no error)*/ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str); /*push back both texts at once*/ void lodepng_clear_text(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str); /*push back the 4 texts of 1 chunk at once*/ void lodepng_clear_itext(LodePNGInfo* info); /*use this to clear the itexts again after you filled them in*/ /*replaces if exists*/ unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size); void lodepng_clear_icc(LodePNGInfo* info); /*use this to clear the texts again after you filled them in*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /* Converts raw buffer from one color type to another color type, based on LodePNGColorMode structs to describe the input and output color type. See the reference manual at the end of this header file to see which color conversions are supported. return value = LodePNG error code (0 if all went ok, an error if the conversion isn't supported) The out buffer must have size (w * h * bpp + 7) / 8, where bpp is the bits per pixel of the output color type (lodepng_get_bpp). For < 8 bpp images, there should not be padding bits at the end of scanlines. For 16-bit per channel colors, uses big endian format like PNG does. Return value is LodePNG error code */ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h); #ifdef LODEPNG_COMPILE_DECODER /* Settings for the decoder. This contains settings for the PNG and the Zlib decoder, but not the Info settings from the Info structs. */ typedef struct LodePNGDecoderSettings { LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ unsigned ignore_crc; /*ignore CRC checksums*/ unsigned ignore_critical; /*ignore unknown critical chunks*/ unsigned ignore_end; /*ignore issues at end of file if possible (missing IEND chunk, too large chunk, ...)*/ /* TODO: make a system involving warnings with levels and a strict mode instead. Other potentially recoverable errors: srgb rendering intent value, size of content of ancillary chunks, more than 79 characters for some strings, placement/combination rules for ancillary chunks, crc of unknown chunks, allowed characters in string keys, etc... */ unsigned color_convert; /*whether to convert the PNG to the color type you want. Default: yes*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned read_text_chunks; /*if false but remember_unknown_chunks is true, they're stored in the unknown chunks*/ /*store all bytes from unknown chunks in the LodePNGInfo (off by default, useful for a png editor)*/ unsigned remember_unknown_chunks; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGDecoderSettings; void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ typedef enum LodePNGFilterStrategy { /*every filter at zero*/ LFS_ZERO, /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ LFS_MINSUM, /*Use the filter type that gives smallest Shannon entropy for this scanline. Depending on the image, this is better or worse than minsum.*/ LFS_ENTROPY, /* Brute-force-search PNG filters by compressing each filter for each scanline. Experimental, very slow, and only rarely gives better compression than MINSUM. */ LFS_BRUTE_FORCE, /*use predefined_filters buffer: you specify the filter type for each scanline*/ LFS_PREDEFINED } LodePNGFilterStrategy; /*Gives characteristics about the integer RGBA colors of the image (count, alpha channel usage, bit depth, ...), which helps decide which color model to use for encoding. Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms. NOTE: This is not related to the ICC color profile, search "iccp_profile" instead to find the ICC/chromacity/... fields in this header file.*/ typedef struct LodePNGColorProfile { unsigned colored; /*not greyscale*/ unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ unsigned short key_g; unsigned short key_b; unsigned alpha; /*image is not opaque and alpha channel or alpha palette required*/ unsigned numcolors; /*amount of colors, up to 257. Not valid if bits == 16.*/ unsigned char palette[1024]; /*Remembers up to the first 256 RGBA colors, in no particular order*/ unsigned bits; /*bits per channel (not for palette). 1,2 or 4 for greyscale only. 16 if 16-bit per channel required.*/ size_t numpixels; } LodePNGColorProfile; void lodepng_color_profile_init(LodePNGColorProfile* profile); /*Get a LodePNGColorProfile of the image. The profile must already have been inited. NOTE: This is not related to the ICC color profile, search "iccp_profile" instead to find the ICC/chromacity/... fields in this header file.*/ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in); /*The function LodePNG uses internally to decide the PNG color with auto_convert. Chooses an optimal color model, e.g. grey if only grey pixels, palette if < 256 colors, ...*/ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in); /*Settings for the encoder.*/ typedef struct LodePNGEncoderSettings { LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ /*If true, follows the official PNG heuristic: if the PNG uses a palette or lower than 8 bit depth, set all filters to zero. Otherwise use the filter_strategy. Note that to completely follow the official PNG heuristic, filter_palette_zero must be true and filter_strategy must be LFS_MINSUM*/ unsigned filter_palette_zero; /*Which filter strategy to use when not using zeroes due to filter_palette_zero. Set filter_palette_zero to 0 to ensure always using your chosen strategy. Default: LFS_MINSUM*/ LodePNGFilterStrategy filter_strategy; /*used if filter_strategy is LFS_PREDEFINED. In that case, this must point to a buffer with the same length as the amount of scanlines in the image, and each value must <= 5. You have to cleanup this buffer, LodePNG will never free it. Don't forget that filter_palette_zero must be set to 0 to ensure this is also used on palette or low bitdepth images.*/ const unsigned char* predefined_filters; /*force creating a PLTE chunk if colortype is 2 or 6 (= a suggested palette). If colortype is 3, PLTE is _always_ created.*/ unsigned force_palette; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*add LodePNG identifier and version as a text chunk, for debugging*/ unsigned add_id; /*encode text chunks as zTXt chunks instead of tEXt chunks, and use compression in iTXt chunks*/ unsigned text_compression; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } LodePNGEncoderSettings; void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) /*The settings, state and information for extended encoding and decoding.*/ typedef struct LodePNGState { #ifdef LODEPNG_COMPILE_DECODER LodePNGDecoderSettings decoder; /*the decoding settings*/ #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER LodePNGEncoderSettings encoder; /*the encoding settings*/ #endif /*LODEPNG_COMPILE_ENCODER*/ LodePNGColorMode info_raw; /*specifies the format in which you would like to get the raw pixel buffer*/ LodePNGInfo info_png; /*info of the PNG image obtained after decoding*/ unsigned error; #ifdef LODEPNG_COMPILE_CPP /* For the lodepng::State subclass. */ virtual ~LodePNGState() {} #endif } LodePNGState; /*init, cleanup and copy functions to use with this struct*/ void lodepng_state_init(LodePNGState* state); void lodepng_state_cleanup(LodePNGState* state); void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source); #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #ifdef LODEPNG_COMPILE_DECODER /* Same as lodepng_decode_memory, but uses a LodePNGState to allow custom settings and getting much more information about the PNG image and color mode. */ unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); /* Read the PNG header, but not the actual data. This returns only the information that is in the IHDR chunk of the PNG, such as width, height and color type. The information is placed in the info_png field of the LodePNGState. */ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /*This function allocates the out buffer with standard malloc and stores the size in *outsize.*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state); #endif /*LODEPNG_COMPILE_ENCODER*/ /* The lodepng_chunk functions are normally not needed, except to traverse the unknown chunks stored in the LodePNGInfo struct, or add new ones to it. It also allows traversing the chunks of an encoded PNG file yourself. The chunk pointer always points to the beginning of the chunk itself, that is the first byte of the 4 length bytes. In the PNG file format, chunks have the following format: -4 bytes length: length of the data of the chunk in bytes (chunk itself is 12 bytes longer) -4 bytes chunk name (ASCII a-z,A-Z only, see below) -length bytes of data (may be 0 bytes if length was 0) -4 bytes of CRC, computed on chunk name + data The first chunk starts at the 8th byte of the PNG file, the entire rest of the file exists out of concatenated chunks with the above format. PNG standard chunk ASCII naming conventions: -First byte: uppercase = critical, lowercase = ancillary -Second byte: uppercase = public, lowercase = private -Third byte: must be uppercase -Fourth byte: uppercase = unsafe to copy, lowercase = safe to copy */ /* Gets the length of the data of the chunk. Total chunk length has 12 bytes more. There must be at least 4 bytes to read from. If the result value is too large, it may be corrupt data. */ unsigned lodepng_chunk_length(const unsigned char* chunk); /*puts the 4-byte type in null terminated string*/ void lodepng_chunk_type(char type[5], const unsigned char* chunk); /*check if the type is the given type*/ unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type); /*0: it's one of the critical chunk types, 1: it's an ancillary chunk (see PNG standard)*/ unsigned char lodepng_chunk_ancillary(const unsigned char* chunk); /*0: public, 1: private (see PNG standard)*/ unsigned char lodepng_chunk_private(const unsigned char* chunk); /*0: the chunk is unsafe to copy, 1: the chunk is safe to copy (see PNG standard)*/ unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk); /*get pointer to the data of the chunk, where the input points to the header of the chunk*/ unsigned char* lodepng_chunk_data(unsigned char* chunk); const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk); /*returns 0 if the crc is correct, 1 if it's incorrect (0 for OK as usual!)*/ unsigned lodepng_chunk_check_crc(const unsigned char* chunk); /*generates the correct CRC from the data and puts it in the last 4 bytes of the chunk*/ void lodepng_chunk_generate_crc(unsigned char* chunk); /* Iterate to next chunks, allows iterating through all chunks of the PNG file. Expects at least 4 readable bytes of memory in the input pointer. Will output pointer to the start of the next chunk or the end of the file if there is no more chunk after this. Start this process at the 8th byte of the PNG file. In a non-corrupt PNG file, the last chunk should have name "IEND". */ unsigned char* lodepng_chunk_next(unsigned char* chunk); const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk); /* Appends chunk to the data in out. The given chunk should already have its chunk header. The out variable and outlength are updated to reflect the new reallocated buffer. Returns error code (0 if it went ok) */ unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk); /* Appends new chunk to out. The chunk to append is given by giving its length, type and data separately. The type is a 4-letter string. The out variable and outlength are updated to reflect the new reallocated buffer. Returne error code (0 if it went ok) */ unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data); /*Calculate CRC32 of buffer*/ unsigned lodepng_crc32(const unsigned char* buf, size_t len); #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ZLIB /* This zlib part can be used independently to zlib compress and decompress a buffer. It cannot be used to create gzip files however, and it only supports the part of zlib that is required for PNG, it does not support dictionaries. */ #ifdef LODEPNG_COMPILE_DECODER /*Inflate a buffer. Inflate is the decompression step of deflate. Out buffer must be freed after use.*/ unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); /* Decompresses Zlib data. Reallocates the out buffer and appends the data. The data must be according to the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Compresses data with Zlib. Reallocates the out buffer and appends the data. Zlib adds a small header and trailer around the deflate data. The data is output in the format of the zlib specification. Either, *out must be NULL and *outsize must be 0, or, *out must be a valid buffer and *outsize its size in bytes. out must be freed by user after usage. */ unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); /* Find length-limited Huffman code for given frequencies. This function is in the public interface only for tests, it's used internally by lodepng_deflate. */ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen); /*Compress a buffer with deflate. See RFC 1951. Out buffer must be freed after use.*/ unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings); #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into buffer. The function allocates the out buffer, and after usage you should free it. out: output parameter, contains pointer to loaded buffer. outsize: output parameter, size of the allocated out buffer filename: the path to the file to load return value: error code (0 means ok) */ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename); /* Save a file from buffer to disk. Warning, if it exists, this function overwrites the file without warning! buffer: the buffer to write buffersize: size of the buffer to write filename: the path to the file to save to return value: error code (0 means ok) */ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename); #endif /*LODEPNG_COMPILE_DISK*/ #ifdef LODEPNG_COMPILE_CPP /* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ namespace lodepng { #ifdef LODEPNG_COMPILE_PNG class State : public LodePNGState { public: State(); State(const State& other); virtual ~State(); State& operator=(const State& other); }; #ifdef LODEPNG_COMPILE_DECODER /* Same as other lodepng::decode, but using a State for more settings and information. */ unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const unsigned char* in, size_t insize); unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const std::vector& in); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* Same as other lodepng::encode, but using a State for more settings and information. */ unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, State& state); unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, State& state); #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DISK /* Load a file from disk into an std::vector. return value: error code (0 means ok) */ unsigned load_file(std::vector& buffer, const std::string& filename); /* Save the binary data in an std::vector to a file on disk. The file is overwritten without warning. */ unsigned save_file(const std::vector& buffer, const std::string& filename); #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_PNG */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_DECODER /* Zlib-decompress an unsigned char buffer */ unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); /* Zlib-decompress an std::vector */ unsigned decompress(std::vector& out, const std::vector& in, const LodePNGDecompressSettings& settings = lodepng_default_decompress_settings); #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER /* Zlib-compress an unsigned char buffer */ unsigned compress(std::vector& out, const unsigned char* in, size_t insize, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); /* Zlib-compress an std::vector */ unsigned compress(std::vector& out, const std::vector& in, const LodePNGCompressSettings& settings = lodepng_default_compress_settings); #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ZLIB */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ /* TODO: [.] test if there are no memory leaks or security exploits - done a lot but needs to be checked often [.] check compatibility with various compilers - done but needs to be redone for every newer version [X] converting color to 16-bit per channel types [X] support color profile chunk types (but never let them touch RGB values by default) [ ] support all public PNG chunk types [ ] make sure encoder generates no chunks with size > (2^31)-1 [ ] partial decoding (stream processing) [X] let the "isFullyOpaque" function check color keys and transparent palettes too [X] better name for the variables "codes", "codesD", "codelengthcodes", "clcl" and "lldl" [ ] don't stop decoding on errors like 69, 57, 58 (make warnings) [ ] make warnings like: oob palette, checksum fail, data after iend, wrong/unknown crit chunk, no null terminator in text, ... [ ] errors with line numbers (and version) [ ] let the C++ wrapper catch exceptions coming from the standard library and return LodePNG error codes [ ] allow user to provide custom color conversion functions, e.g. for premultiplied alpha, padding bits or not, ... [ ] allow user to give data (void*) to custom allocator */ #endif /*LODEPNG_H inclusion guard*/ /* LodePNG Documentation --------------------- 0. table of contents -------------------- 1. about 1.1. supported features 1.2. features not supported 2. C and C++ version 3. security 4. decoding 5. encoding 6. color conversions 6.1. PNG color types 6.2. color conversions 6.3. padding bits 6.4. A note about 16-bits per channel and endianness 7. error values 8. chunks and PNG editing 9. compiler support 10. examples 10.1. decoder C++ example 10.2. decoder C example 11. state settings reference 12. changes 13. contact information 1. about -------- PNG is a file format to store raster images losslessly with good compression, supporting different color types and alpha channel. LodePNG is a PNG codec according to the Portable Network Graphics (PNG) Specification (Second Edition) - W3C Recommendation 10 November 2003. The specifications used are: *) Portable Network Graphics (PNG) Specification (Second Edition): http://www.w3.org/TR/2003/REC-PNG-20031110 *) RFC 1950 ZLIB Compressed Data Format version 3.3: http://www.gzip.org/zlib/rfc-zlib.html *) RFC 1951 DEFLATE Compressed Data Format Specification ver 1.3: http://www.gzip.org/zlib/rfc-deflate.html The most recent version of LodePNG can currently be found at http://lodev.org/lodepng/ LodePNG works both in C (ISO C90) and C++, with a C++ wrapper that adds extra functionality. LodePNG exists out of two files: -lodepng.h: the header file for both C and C++ -lodepng.c(pp): give it the name lodepng.c or lodepng.cpp (or .cc) depending on your usage If you want to start using LodePNG right away without reading this doc, get the examples from the LodePNG website to see how to use it in code, or check the smaller examples in chapter 13 here. LodePNG is simple but only supports the basic requirements. To achieve simplicity, the following design choices were made: There are no dependencies on any external library. There are functions to decode and encode a PNG with a single function call, and extended versions of these functions taking a LodePNGState struct allowing to specify or get more information. By default the colors of the raw image are always RGB or RGBA, no matter what color type the PNG file uses. To read and write files, there are simple functions to convert the files to/from buffers in memory. This all makes LodePNG suitable for loading textures in games, demos and small programs, ... It's less suitable for full fledged image editors, loading PNGs over network (it requires all the image data to be available before decoding can begin), life-critical systems, ... 1.1. supported features ----------------------- The following features are supported by the decoder: *) decoding of PNGs with any color type, bit depth and interlace mode, to a 24- or 32-bit color raw image, or the same color type as the PNG *) encoding of PNGs, from any raw image to 24- or 32-bit color, or the same color type as the raw image *) Adam7 interlace and deinterlace for any color type *) loading the image from harddisk or decoding it from a buffer from other sources than harddisk *) support for alpha channels, including RGBA color model, translucent palettes and color keying *) zlib decompression (inflate) *) zlib compression (deflate) *) CRC32 and ADLER32 checksums *) handling of unknown chunks, allowing making a PNG editor that stores custom and unknown chunks. *) the following chunks are supported (generated/interpreted) by both encoder and decoder: IHDR: header information PLTE: color palette IDAT: pixel data IEND: the final chunk tRNS: transparency for palettized images tEXt: textual information zTXt: compressed textual information iTXt: international textual information bKGD: suggested background color pHYs: physical dimensions tIME: modification time 1.2. features not supported --------------------------- The following features are _not_ supported: *) some features needed to make a conformant PNG-Editor might be still missing. *) partial loading/stream processing. All data must be available and is processed in one call. *) The following public chunks are not supported but treated as unknown chunks by LodePNG cHRM, gAMA, iCCP, sRGB, sBIT, hIST, sPLT Some of these are not supported on purpose: LodePNG wants to provide the RGB values stored in the pixels, not values modified by system dependent gamma or color models. 2. C and C++ version -------------------- The C version uses buffers allocated with alloc that you need to free() yourself. You need to use init and cleanup functions for each struct whenever using a struct from the C version to avoid exploits and memory leaks. The C++ version has extra functions with std::vectors in the interface and the lodepng::State class which is a LodePNGState with constructor and destructor. These files work without modification for both C and C++ compilers because all the additional C++ code is in "#ifdef __cplusplus" blocks that make C-compilers ignore it, and the C code is made to compile both with strict ISO C90 and C++. To use the C++ version, you need to rename the source file to lodepng.cpp (instead of lodepng.c), and compile it with a C++ compiler. To use the C version, you need to rename the source file to lodepng.c (instead of lodepng.cpp), and compile it with a C compiler. 3. Security ----------- Even if carefully designed, it's always possible that LodePNG contains possible exploits. If you discover one, please let me know, and it will be fixed. When using LodePNG, care has to be taken with the C version of LodePNG, as well as the C-style structs when working with C++. The following conventions are used for all C-style structs: -if a struct has a corresponding init function, always call the init function when making a new one -if a struct has a corresponding cleanup function, call it before the struct disappears to avoid memory leaks -if a struct has a corresponding copy function, use the copy function instead of "=". The destination must also be inited already. 4. Decoding ----------- Decoding converts a PNG compressed image to a raw pixel buffer. Most documentation on using the decoder is at its declarations in the header above. For C, simple decoding can be done with functions such as lodepng_decode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_decode. For C++, all decoding can be done with the various lodepng::decode functions, and lodepng::State can be used for advanced features. When using the LodePNGState, it uses the following fields for decoding: *) LodePNGInfo info_png: it stores extra information about the PNG (the input) in here *) LodePNGColorMode info_raw: here you can say what color mode of the raw image (the output) you want to get *) LodePNGDecoderSettings decoder: you can specify a few extra settings for the decoder to use LodePNGInfo info_png -------------------- After decoding, this contains extra information of the PNG image, except the actual pixels, width and height because these are already gotten directly from the decoder functions. It contains for example the original color type of the PNG image, text comments, suggested background color, etc... More details about the LodePNGInfo struct are at its declaration documentation. LodePNGColorMode info_raw ------------------------- When decoding, here you can specify which color type you want the resulting raw image to be. If this is different from the colortype of the PNG, then the decoder will automatically convert the result. This conversion always works, except if you want it to convert a color PNG to greyscale or to a palette with missing colors. By default, 32-bit color is used for the result. LodePNGDecoderSettings decoder ------------------------------ The settings can be used to ignore the errors created by invalid CRC and Adler32 chunks, and to disable the decoding of tEXt chunks. There's also a setting color_convert, true by default. If false, no conversion is done, the resulting data will be as it was in the PNG (after decompression) and you'll have to puzzle the colors of the pixels together yourself using the color type information in the LodePNGInfo. 5. Encoding ----------- Encoding converts a raw pixel buffer to a PNG compressed image. Most documentation on using the encoder is at its declarations in the header above. For C, simple encoding can be done with functions such as lodepng_encode32, and more advanced decoding can be done with the struct LodePNGState and lodepng_encode. For C++, all encoding can be done with the various lodepng::encode functions, and lodepng::State can be used for advanced features. Like the decoder, the encoder can also give errors. However it gives less errors since the encoder input is trusted, the decoder input (a PNG image that could be forged by anyone) is not trusted. When using the LodePNGState, it uses the following fields for encoding: *) LodePNGInfo info_png: here you specify how you want the PNG (the output) to be. *) LodePNGColorMode info_raw: here you say what color type of the raw image (the input) has *) LodePNGEncoderSettings encoder: you can specify a few settings for the encoder to use LodePNGInfo info_png -------------------- When encoding, you use this the opposite way as when decoding: for encoding, you fill in the values you want the PNG to have before encoding. By default it's not needed to specify a color type for the PNG since it's automatically chosen, but it's possible to choose it yourself given the right settings. The encoder will not always exactly match the LodePNGInfo struct you give, it tries as close as possible. Some things are ignored by the encoder. The encoder uses, for example, the following settings from it when applicable: colortype and bitdepth, text chunks, time chunk, the color key, the palette, the background color, the interlace method, unknown chunks, ... When encoding to a PNG with colortype 3, the encoder will generate a PLTE chunk. If the palette contains any colors for which the alpha channel is not 255 (so there are translucent colors in the palette), it'll add a tRNS chunk. LodePNGColorMode info_raw ------------------------- You specify the color type of the raw image that you give to the input here, including a possible transparent color key and palette you happen to be using in your raw image data. By default, 32-bit color is assumed, meaning your input has to be in RGBA format with 4 bytes (unsigned chars) per pixel. LodePNGEncoderSettings encoder ------------------------------ The following settings are supported (some are in sub-structs): *) auto_convert: when this option is enabled, the encoder will automatically choose the smallest possible color mode (including color key) that can encode the colors of all pixels without information loss. *) btype: the block type for LZ77. 0 = uncompressed, 1 = fixed huffman tree, 2 = dynamic huffman tree (best compression). Should be 2 for proper compression. *) use_lz77: whether or not to use LZ77 for compressed block types. Should be true for proper compression. *) windowsize: the window size used by the LZ77 encoder (1 - 32768). Has value 2048 by default, but can be set to 32768 for better, but slow, compression. *) force_palette: if colortype is 2 or 6, you can make the encoder write a PLTE chunk if force_palette is true. This can used as suggested palette to convert to by viewers that don't support more than 256 colors (if those still exist) *) add_id: add text chunk "Encoder: LodePNG " to the image. *) text_compression: default 1. If 1, it'll store texts as zTXt instead of tEXt chunks. zTXt chunks use zlib compression on the text. This gives a smaller result on large texts but a larger result on small texts (such as a single program name). It's all tEXt or all zTXt though, there's no separate setting per text yet. 6. color conversions -------------------- An important thing to note about LodePNG, is that the color type of the PNG, and the color type of the raw image, are completely independent. By default, when you decode a PNG, you get the result as a raw image in the color type you want, no matter whether the PNG was encoded with a palette, greyscale or RGBA color. And if you encode an image, by default LodePNG will automatically choose the PNG color type that gives good compression based on the values of colors and amount of colors in the image. It can be configured to let you control it instead as well, though. To be able to do this, LodePNG does conversions from one color mode to another. It can convert from almost any color type to any other color type, except the following conversions: RGB to greyscale is not supported, and converting to a palette when the palette doesn't have a required color is not supported. This is not supported on purpose: this is information loss which requires a color reduction algorithm that is beyong the scope of a PNG encoder (yes, RGB to grey is easy, but there are multiple ways if you want to give some channels more weight). By default, when decoding, you get the raw image in 32-bit RGBA or 24-bit RGB color, no matter what color type the PNG has. And by default when encoding, LodePNG automatically picks the best color model for the output PNG, and expects the input image to be 32-bit RGBA or 24-bit RGB. So, unless you want to control the color format of the images yourself, you can skip this chapter. 6.1. PNG color types -------------------- A PNG image can have many color types, ranging from 1-bit color to 64-bit color, as well as palettized color modes. After the zlib decompression and unfiltering in the PNG image is done, the raw pixel data will have that color type and thus a certain amount of bits per pixel. If you want the output raw image after decoding to have another color type, a conversion is done by LodePNG. The PNG specification gives the following color types: 0: greyscale, bit depths 1, 2, 4, 8, 16 2: RGB, bit depths 8 and 16 3: palette, bit depths 1, 2, 4 and 8 4: greyscale with alpha, bit depths 8 and 16 6: RGBA, bit depths 8 and 16 Bit depth is the amount of bits per pixel per color channel. So the total amount of bits per pixel is: amount of channels * bitdepth. 6.2. color conversions ---------------------- As explained in the sections about the encoder and decoder, you can specify color types and bit depths in info_png and info_raw to change the default behaviour. If, when decoding, you want the raw image to be something else than the default, you need to set the color type and bit depth you want in the LodePNGColorMode, or the parameters colortype and bitdepth of the simple decoding function. If, when encoding, you use another color type than the default in the raw input image, you need to specify its color type and bit depth in the LodePNGColorMode of the raw image, or use the parameters colortype and bitdepth of the simple encoding function. If, when encoding, you don't want LodePNG to choose the output PNG color type but control it yourself, you need to set auto_convert in the encoder settings to false, and specify the color type you want in the LodePNGInfo of the encoder (including palette: it can generate a palette if auto_convert is true, otherwise not). If the input and output color type differ (whether user chosen or auto chosen), LodePNG will do a color conversion, which follows the rules below, and may sometimes result in an error. To avoid some confusion: -the decoder converts from PNG to raw image -the encoder converts from raw image to PNG -the colortype and bitdepth in LodePNGColorMode info_raw, are those of the raw image -the colortype and bitdepth in the color field of LodePNGInfo info_png, are those of the PNG -when encoding, the color type in LodePNGInfo is ignored if auto_convert is enabled, it is automatically generated instead -when decoding, the color type in LodePNGInfo is set by the decoder to that of the original PNG image, but it can be ignored since the raw image has the color type you requested instead -if the color type of the LodePNGColorMode and PNG image aren't the same, a conversion between the color types is done if the color types are supported. If it is not supported, an error is returned. If the types are the same, no conversion is done. -even though some conversions aren't supported, LodePNG supports loading PNGs from any colortype and saving PNGs to any colortype, sometimes it just requires preparing the raw image correctly before encoding. -both encoder and decoder use the same color converter. Non supported color conversions: -color to greyscale: no error is thrown, but the result will look ugly because only the red channel is taken -anything to palette when that palette does not have that color in it: in this case an error is thrown Supported color conversions: -anything to 8-bit RGB, 8-bit RGBA, 16-bit RGB, 16-bit RGBA -any grey or grey+alpha, to grey or grey+alpha -anything to a palette, as long as the palette has the requested colors in it -removing alpha channel -higher to smaller bitdepth, and vice versa If you want no color conversion to be done (e.g. for speed or control): -In the encoder, you can make it save a PNG with any color type by giving the raw color mode and LodePNGInfo the same color mode, and setting auto_convert to false. -In the decoder, you can make it store the pixel data in the same color type as the PNG has, by setting the color_convert setting to false. Settings in info_raw are then ignored. The function lodepng_convert does the color conversion. It is available in the interface but normally isn't needed since the encoder and decoder already call it. 6.3. padding bits ----------------- In the PNG file format, if a less than 8-bit per pixel color type is used and the scanlines have a bit amount that isn't a multiple of 8, then padding bits are used so that each scanline starts at a fresh byte. But that is NOT true for the LodePNG raw input and output. The raw input image you give to the encoder, and the raw output image you get from the decoder will NOT have these padding bits, e.g. in the case of a 1-bit image with a width of 7 pixels, the first pixel of the second scanline will the the 8th bit of the first byte, not the first bit of a new byte. 6.4. A note about 16-bits per channel and endianness ---------------------------------------------------- LodePNG uses unsigned char arrays for 16-bit per channel colors too, just like for any other color format. The 16-bit values are stored in big endian (most significant byte first) in these arrays. This is the opposite order of the little endian used by x86 CPU's. LodePNG always uses big endian because the PNG file format does so internally. Conversions to other formats than PNG uses internally are not supported by LodePNG on purpose, there are myriads of formats, including endianness of 16-bit colors, the order in which you store R, G, B and A, and so on. Supporting and converting to/from all that is outside the scope of LodePNG. This may mean that, depending on your use case, you may want to convert the big endian output of LodePNG to little endian with a for loop. This is certainly not always needed, many applications and libraries support big endian 16-bit colors anyway, but it means you cannot simply cast the unsigned char* buffer to an unsigned short* buffer on x86 CPUs. 7. error values --------------- All functions in LodePNG that return an error code, return 0 if everything went OK, or a non-zero code if there was an error. The meaning of the LodePNG error values can be retrieved with the function lodepng_error_text: given the numerical error code, it returns a description of the error in English as a string. Check the implementation of lodepng_error_text to see the meaning of each code. 8. chunks and PNG editing ------------------------- If you want to add extra chunks to a PNG you encode, or use LodePNG for a PNG editor that should follow the rules about handling of unknown chunks, or if your program is able to read other types of chunks than the ones handled by LodePNG, then that's possible with the chunk functions of LodePNG. A PNG chunk has the following layout: 4 bytes length 4 bytes type name length bytes data 4 bytes CRC 8.1. iterating through chunks ----------------------------- If you have a buffer containing the PNG image data, then the first chunk (the IHDR chunk) starts at byte number 8 of that buffer. The first 8 bytes are the signature of the PNG and are not part of a chunk. But if you start at byte 8 then you have a chunk, and can check the following things of it. NOTE: none of these functions check for memory buffer boundaries. To avoid exploits, always make sure the buffer contains all the data of the chunks. When using lodepng_chunk_next, make sure the returned value is within the allocated memory. unsigned lodepng_chunk_length(const unsigned char* chunk): Get the length of the chunk's data. The total chunk length is this length + 12. void lodepng_chunk_type(char type[5], const unsigned char* chunk): unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type): Get the type of the chunk or compare if it's a certain type unsigned char lodepng_chunk_critical(const unsigned char* chunk): unsigned char lodepng_chunk_private(const unsigned char* chunk): unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk): Check if the chunk is critical in the PNG standard (only IHDR, PLTE, IDAT and IEND are). Check if the chunk is private (public chunks are part of the standard, private ones not). Check if the chunk is safe to copy. If it's not, then, when modifying data in a critical chunk, unsafe to copy chunks of the old image may NOT be saved in the new one if your program doesn't handle that type of unknown chunk. unsigned char* lodepng_chunk_data(unsigned char* chunk): const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk): Get a pointer to the start of the data of the chunk. unsigned lodepng_chunk_check_crc(const unsigned char* chunk): void lodepng_chunk_generate_crc(unsigned char* chunk): Check if the crc is correct or generate a correct one. unsigned char* lodepng_chunk_next(unsigned char* chunk): const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk): Iterate to the next chunk. This works if you have a buffer with consecutive chunks. Note that these functions do no boundary checking of the allocated data whatsoever, so make sure there is enough data available in the buffer to be able to go to the next chunk. unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk): unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data): These functions are used to create new chunks that are appended to the data in *out that has length *outlength. The append function appends an existing chunk to the new data. The create function creates a new chunk with the given parameters and appends it. Type is the 4-letter name of the chunk. 8.2. chunks in info_png ----------------------- The LodePNGInfo struct contains fields with the unknown chunk in it. It has 3 buffers (each with size) to contain 3 types of unknown chunks: the ones that come before the PLTE chunk, the ones that come between the PLTE and the IDAT chunks, and the ones that come after the IDAT chunks. It's necessary to make the distionction between these 3 cases because the PNG standard forces to keep the ordering of unknown chunks compared to the critical chunks, but does not force any other ordering rules. info_png.unknown_chunks_data[0] is the chunks before PLTE info_png.unknown_chunks_data[1] is the chunks after PLTE, before IDAT info_png.unknown_chunks_data[2] is the chunks after IDAT The chunks in these 3 buffers can be iterated through and read by using the same way described in the previous subchapter. When using the decoder to decode a PNG, you can make it store all unknown chunks if you set the option settings.remember_unknown_chunks to 1. By default, this option is off (0). The encoder will always encode unknown chunks that are stored in the info_png. If you need it to add a particular chunk that isn't known by LodePNG, you can use lodepng_chunk_append or lodepng_chunk_create to the chunk data in info_png.unknown_chunks_data[x]. Chunks that are known by LodePNG should not be added in that way. E.g. to make LodePNG add a bKGD chunk, set background_defined to true and add the correct parameters there instead. 9. compiler support ------------------- No libraries other than the current standard C library are needed to compile LodePNG. For the C++ version, only the standard C++ library is needed on top. Add the files lodepng.c(pp) and lodepng.h to your project, include lodepng.h where needed, and your program can read/write PNG files. It is compatible with C90 and up, and C++03 and up. If performance is important, use optimization when compiling! For both the encoder and decoder, this makes a large difference. Make sure that LodePNG is compiled with the same compiler of the same version and with the same settings as the rest of the program, or the interfaces with std::vectors and std::strings in C++ can be incompatible. CHAR_BITS must be 8 or higher, because LodePNG uses unsigned chars for octets. *) gcc and g++ LodePNG is developed in gcc so this compiler is natively supported. It gives no warnings with compiler options "-Wall -Wextra -pedantic -ansi", with gcc and g++ version 4.7.1 on Linux, 32-bit and 64-bit. *) Clang Fully supported and warning-free. *) Mingw The Mingw compiler (a port of gcc for Windows) should be fully supported by LodePNG. *) Visual Studio and Visual C++ Express Edition LodePNG should be warning-free with warning level W4. Two warnings were disabled with pragmas though: warning 4244 about implicit conversions, and warning 4996 where it wants to use a non-standard function fopen_s instead of the standard C fopen. Visual Studio may want "stdafx.h" files to be included in each source file and give an error "unexpected end of file while looking for precompiled header". This is not standard C++ and will not be added to the stock LodePNG. You can disable it for lodepng.cpp only by right clicking it, Properties, C/C++, Precompiled Headers, and set it to Not Using Precompiled Headers there. NOTE: Modern versions of VS should be fully supported, but old versions, e.g. VS6, are not guaranteed to work. *) Compilers on Macintosh LodePNG has been reported to work both with gcc and LLVM for Macintosh, both for C and C++. *) Other Compilers If you encounter problems on any compilers, feel free to let me know and I may try to fix it if the compiler is modern and standards complient. 10. examples ------------ This decoder example shows the most basic usage of LodePNG. More complex examples can be found on the LodePNG website. 10.1. decoder C++ example ------------------------- #include "lodepng.h" #include int main(int argc, char *argv[]) { const char* filename = argc > 1 ? argv[1] : "test.png"; //load and decode std::vector image; unsigned width, height; unsigned error = lodepng::decode(image, width, height, filename); //if there's an error, display it if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... } 10.2. decoder C example ----------------------- #include "lodepng.h" int main(int argc, char *argv[]) { unsigned error; unsigned char* image; size_t width, height; const char* filename = argc > 1 ? argv[1] : "test.png"; error = lodepng_decode32_file(&image, &width, &height, filename); if(error) printf("decoder error %u: %s\n", error, lodepng_error_text(error)); / * use image here * / free(image); return 0; } 11. state settings reference ---------------------------- A quick reference of some settings to set on the LodePNGState For decoding: state.decoder.zlibsettings.ignore_adler32: ignore ADLER32 checksums state.decoder.zlibsettings.custom_...: use custom inflate function state.decoder.ignore_crc: ignore CRC checksums state.decoder.ignore_critical: ignore unknown critical chunks state.decoder.ignore_end: ignore missing IEND chunk. May fail if this corruption causes other errors state.decoder.color_convert: convert internal PNG color to chosen one state.decoder.read_text_chunks: whether to read in text metadata chunks state.decoder.remember_unknown_chunks: whether to read in unknown chunks state.info_raw.colortype: desired color type for decoded image state.info_raw.bitdepth: desired bit depth for decoded image state.info_raw....: more color settings, see struct LodePNGColorMode state.info_png....: no settings for decoder but ouput, see struct LodePNGInfo For encoding: state.encoder.zlibsettings.btype: disable compression by setting it to 0 state.encoder.zlibsettings.use_lz77: use LZ77 in compression state.encoder.zlibsettings.windowsize: tweak LZ77 windowsize state.encoder.zlibsettings.minmatch: tweak min LZ77 length to match state.encoder.zlibsettings.nicematch: tweak LZ77 match where to stop searching state.encoder.zlibsettings.lazymatching: try one more LZ77 matching state.encoder.zlibsettings.custom_...: use custom deflate function state.encoder.auto_convert: choose optimal PNG color type, if 0 uses info_png state.encoder.filter_palette_zero: PNG filter strategy for palette state.encoder.filter_strategy: PNG filter strategy to encode with state.encoder.force_palette: add palette even if not encoding to one state.encoder.add_id: add LodePNG identifier and version as a text chunk state.encoder.text_compression: use compressed text chunks for metadata state.info_raw.colortype: color type of raw input image you provide state.info_raw.bitdepth: bit depth of raw input image you provide state.info_raw: more color settings, see struct LodePNGColorMode state.info_png.color.colortype: desired color type if auto_convert is false state.info_png.color.bitdepth: desired bit depth if auto_convert is false state.info_png.color....: more color settings, see struct LodePNGColorMode state.info_png....: more PNG related settings, see struct LodePNGInfo 12. changes ----------- The version number of LodePNG is the date of the change given in the format yyyymmdd. Some changes aren't backwards compatible. Those are indicated with a (!) symbol. *) 19 aug 2018 (!): fixed color mode bKGD is encoded with and made it use palette index in case of palette. *) 10 aug 2018 (!): added support for gAMA, cHRM, sRGB and iCCP chunks. This change is backwards compatible unless you relied on unknown_chunks for those. *) 11 jun 2018: less restrictive check for pixel size integer overflow *) 14 jan 2018: allow optionally ignoring a few more recoverable errors *) 17 sep 2017: fix memory leak for some encoder input error cases *) 27 nov 2016: grey+alpha auto color model detection bugfix *) 18 apr 2016: Changed qsort to custom stable sort (for platforms w/o qsort). *) 09 apr 2016: Fixed colorkey usage detection, and better file loading (within the limits of pure C90). *) 08 dec 2015: Made load_file function return error if file can't be opened. *) 24 okt 2015: Bugfix with decoding to palette output. *) 18 apr 2015: Boundary PM instead of just package-merge for faster encoding. *) 23 aug 2014: Reduced needless memory usage of decoder. *) 28 jun 2014: Removed fix_png setting, always support palette OOB for simplicity. Made ColorProfile public. *) 09 jun 2014: Faster encoder by fixing hash bug and more zeros optimization. *) 22 dec 2013: Power of two windowsize required for optimization. *) 15 apr 2013: Fixed bug with LAC_ALPHA and color key. *) 25 mar 2013: Added an optional feature to ignore some PNG errors (fix_png). *) 11 mar 2013 (!): Bugfix with custom free. Changed from "my" to "lodepng_" prefix for the custom allocators and made it possible with a new #define to use custom ones in your project without needing to change lodepng's code. *) 28 jan 2013: Bugfix with color key. *) 27 okt 2012: Tweaks in text chunk keyword length error handling. *) 8 okt 2012 (!): Added new filter strategy (entropy) and new auto color mode. (no palette). Better deflate tree encoding. New compression tweak settings. Faster color conversions while decoding. Some internal cleanups. *) 23 sep 2012: Reduced warnings in Visual Studio a little bit. *) 1 sep 2012 (!): Removed #define's for giving custom (de)compression functions and made it work with function pointers instead. *) 23 jun 2012: Added more filter strategies. Made it easier to use custom alloc and free functions and toggle #defines from compiler flags. Small fixes. *) 6 may 2012 (!): Made plugging in custom zlib/deflate functions more flexible. *) 22 apr 2012 (!): Made interface more consistent, renaming a lot. Removed redundant C++ codec classes. Reduced amount of structs. Everything changed, but it is cleaner now imho and functionality remains the same. Also fixed several bugs and shrunk the implementation code. Made new samples. *) 6 nov 2011 (!): By default, the encoder now automatically chooses the best PNG color model and bit depth, based on the amount and type of colors of the raw image. For this, autoLeaveOutAlphaChannel replaced by auto_choose_color. *) 9 okt 2011: simpler hash chain implementation for the encoder. *) 8 sep 2011: lz77 encoder lazy matching instead of greedy matching. *) 23 aug 2011: tweaked the zlib compression parameters after benchmarking. A bug with the PNG filtertype heuristic was fixed, so that it chooses much better ones (it's quite significant). A setting to do an experimental, slow, brute force search for PNG filter types is added. *) 17 aug 2011 (!): changed some C zlib related function names. *) 16 aug 2011: made the code less wide (max 120 characters per line). *) 17 apr 2011: code cleanup. Bugfixes. Convert low to 16-bit per sample colors. *) 21 feb 2011: fixed compiling for C90. Fixed compiling with sections disabled. *) 11 dec 2010: encoding is made faster, based on suggestion by Peter Eastman to optimize long sequences of zeros. *) 13 nov 2010: added LodePNG_InfoColor_hasPaletteAlpha and LodePNG_InfoColor_canHaveAlpha functions for convenience. *) 7 nov 2010: added LodePNG_error_text function to get error code description. *) 30 okt 2010: made decoding slightly faster *) 26 okt 2010: (!) changed some C function and struct names (more consistent). Reorganized the documentation and the declaration order in the header. *) 08 aug 2010: only changed some comments and external samples. *) 05 jul 2010: fixed bug thanks to warnings in the new gcc version. *) 14 mar 2010: fixed bug where too much memory was allocated for char buffers. *) 02 sep 2008: fixed bug where it could create empty tree that linux apps could read by ignoring the problem but windows apps couldn't. *) 06 jun 2008: added more error checks for out of memory cases. *) 26 apr 2008: added a few more checks here and there to ensure more safety. *) 06 mar 2008: crash with encoding of strings fixed *) 02 feb 2008: support for international text chunks added (iTXt) *) 23 jan 2008: small cleanups, and #defines to divide code in sections *) 20 jan 2008: support for unknown chunks allowing using LodePNG for an editor. *) 18 jan 2008: support for tIME and pHYs chunks added to encoder and decoder. *) 17 jan 2008: ability to encode and decode compressed zTXt chunks added Also various fixes, such as in the deflate and the padding bits code. *) 13 jan 2008: Added ability to encode Adam7-interlaced images. Improved filtering code of encoder. *) 07 jan 2008: (!) changed LodePNG to use ISO C90 instead of C++. A C++ wrapper around this provides an interface almost identical to before. Having LodePNG be pure ISO C90 makes it more portable. The C and C++ code are together in these files but it works both for C and C++ compilers. *) 29 dec 2007: (!) changed most integer types to unsigned int + other tweaks *) 30 aug 2007: bug fixed which makes this Borland C++ compatible *) 09 aug 2007: some VS2005 warnings removed again *) 21 jul 2007: deflate code placed in new namespace separate from zlib code *) 08 jun 2007: fixed bug with 2- and 4-bit color, and small interlaced images *) 04 jun 2007: improved support for Visual Studio 2005: crash with accessing invalid std::vector element [0] fixed, and level 3 and 4 warnings removed *) 02 jun 2007: made the encoder add a tag with version by default *) 27 may 2007: zlib and png code separated (but still in the same file), simple encoder/decoder functions added for more simple usage cases *) 19 may 2007: minor fixes, some code cleaning, new error added (error 69), moved some examples from here to lodepng_examples.cpp *) 12 may 2007: palette decoding bug fixed *) 24 apr 2007: changed the license from BSD to the zlib license *) 11 mar 2007: very simple addition: ability to encode bKGD chunks. *) 04 mar 2007: (!) tEXt chunk related fixes, and support for encoding palettized PNG images. Plus little interface change with palette and texts. *) 03 mar 2007: Made it encode dynamic Huffman shorter with repeat codes. Fixed a bug where the end code of a block had length 0 in the Huffman tree. *) 26 feb 2007: Huffman compression with dynamic trees (BTYPE 2) now implemented and supported by the encoder, resulting in smaller PNGs at the output. *) 27 jan 2007: Made the Adler-32 test faster so that a timewaste is gone. *) 24 jan 2007: gave encoder an error interface. Added color conversion from any greyscale type to 8-bit greyscale with or without alpha. *) 21 jan 2007: (!) Totally changed the interface. It allows more color types to convert to and is more uniform. See the manual for how it works now. *) 07 jan 2007: Some cleanup & fixes, and a few changes over the last days: encode/decode custom tEXt chunks, separate classes for zlib & deflate, and at last made the decoder give errors for incorrect Adler32 or Crc. *) 01 jan 2007: Fixed bug with encoding PNGs with less than 8 bits per channel. *) 29 dec 2006: Added support for encoding images without alpha channel, and cleaned out code as well as making certain parts faster. *) 28 dec 2006: Added "Settings" to the encoder. *) 26 dec 2006: The encoder now does LZ77 encoding and produces much smaller files now. Removed some code duplication in the decoder. Fixed little bug in an example. *) 09 dec 2006: (!) Placed output parameters of public functions as first parameter. Fixed a bug of the decoder with 16-bit per color. *) 15 okt 2006: Changed documentation structure *) 09 okt 2006: Encoder class added. It encodes a valid PNG image from the given image buffer, however for now it's not compressed. *) 08 sep 2006: (!) Changed to interface with a Decoder class *) 30 jul 2006: (!) LodePNG_InfoPng , width and height are now retrieved in different way. Renamed decodePNG to decodePNGGeneric. *) 29 jul 2006: (!) Changed the interface: image info is now returned as a struct of type LodePNG::LodePNG_Info, instead of a vector, which was a bit clumsy. *) 28 jul 2006: Cleaned the code and added new error checks. Corrected terminology "deflate" into "inflate". *) 23 jun 2006: Added SDL example in the documentation in the header, this example allows easy debugging by displaying the PNG and its transparency. *) 22 jun 2006: (!) Changed way to obtain error value. Added loadFile function for convenience. Made decodePNG32 faster. *) 21 jun 2006: (!) Changed type of info vector to unsigned. Changed position of palette in info vector. Fixed an important bug that happened on PNGs with an uncompressed block. *) 16 jun 2006: Internally changed unsigned into unsigned where needed, and performed some optimizations. *) 07 jun 2006: (!) Renamed functions to decodePNG and placed them in LodePNG namespace. Changed the order of the parameters. Rewrote the documentation in the header. Renamed files to lodepng.cpp and lodepng.h *) 22 apr 2006: Optimized and improved some code *) 07 sep 2005: (!) Changed to std::vector interface *) 12 aug 2005: Initial release (C++, decoder only) 13. contact information ----------------------- Feel free to contact me with suggestions, problems, comments, ... concerning LodePNG. If you encounter a PNG image that doesn't work properly with this decoder, feel free to send it and I'll use it to find and fix the problem. My email address is (puzzle the account and domain together with an @ symbol): Domain: gmail dot com. Account: lode dot vandevenne. Copyright (c) 2005-2018 Lode Vandevenne */ ================================================ FILE: PinBox/PinBox/include/yuv_rgb.h ================================================ // Copyright 2016 Adrien Descamps // Distributed under BSD 3-Clause License // Provide optimized functions to convert images from 8bits yuv420 to rgb24 format // There are a few slightly different variations of the YCbCr color space with different parameters that // change the conversion matrix. // The three most common YCbCr color space, defined by BT.601, BT.709 and JPEG standard are implemented here. // See the respective standards for details // The matrix values used are derived from http://www.equasys.de/colorconversion.html // YUV420 is stored as three separate channels, with U and V (Cb and Cr) subsampled by a 2 factor // For conversion from yuv to rgb, no interpolation is done, and the same UV value are used for 4 rgb pixels. This // is suboptimal for image quality, but by far the fastest method. // For all methods, width and height should be even, if not, the last row/column of the result image won't be affected. // For sse methods, if the width if not divisable by 32, the last (width%32) pixels of each line won't be affected. #include typedef enum { YCBCR_JPEG, YCBCR_601, YCBCR_709 } YCbCrType; #ifdef __cplusplus extern "C" { #endif // yuv to rgb, standard c implementation void yuv420_rgb24_std( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // yuv to rgb, sse implementation // pointers must be 16 byte aligned, and strides must be divisable by 16 void yuv420_rgb24_sse( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // yuv to rgb, sse implementation // pointers do not need to be 16 byte aligned void yuv420_rgb24_sseu( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // rgb to yuv, standard c implementation void rgb24_yuv420_std( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); // rgb to yuv, sse implementation // pointers must be 16 byte aligned, and strides must be divisible by 16 void rgb24_yuv420_sse( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); // rgb to yuv, sse implementation // pointers do not need to be 16 byte aligned void rgb24_yuv420_sseu( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); #ifdef __cplusplus } #endif ================================================ FILE: PinBox/PinBox/source/ConfigManager.cpp ================================================ #include "ConfigManager.h" #define CONFIG_FILE_NAME "pinbox/pinbox.cfg" static ConfigManager* ref; ConfigManager* ConfigManager::Get() { if (ref == nullptr) ref = new ConfigManager(); return ref; } ConfigManager::ConfigManager() { } bool ConfigManager::shouldCreateNewConfigFile() { if (!config_read_file(&_config, CONFIG_FILE_NAME)) { printf("> Config file was not found.\n"); return true; } config_setting_t *root, *setting; root = config_root_setting(&_config); int version = 0; if (!config_lookup_int(&_config, "version", &version)) { printf("> Config do not have version.\n"); return true; } if (version < FORCE_OVERRIDE_VERSION) { printf("> Config file was outdate.\n"); return true; } return false; } void ConfigManager::createNewConfigFile() { config_setting_t *root, *setting; config_destroy(&_config); config_init(&_config); root = config_root_setting(&_config); // server config group setting = config_setting_add(root, "servers", CONFIG_TYPE_LIST); setting = config_setting_add(root, "last_using_server", CONFIG_TYPE_INT); config_setting_set_int(setting, -1); // video config setting = config_setting_add(root, "video_bit_rate", CONFIG_TYPE_INT); config_setting_set_int(setting, 120000); setting = config_setting_add(root, "video_gop", CONFIG_TYPE_INT); config_setting_set_int(setting, 18); setting = config_setting_add(root, "video_max_b_frames", CONFIG_TYPE_INT); config_setting_set_int(setting, 2); // audio setting = config_setting_add(root, "audio_bit_rate", CONFIG_TYPE_INT); config_setting_set_int(setting, 48000); // mode setting = config_setting_add(root, "wait_for_sync", CONFIG_TYPE_BOOL); config_setting_set_bool(setting, true); setting = config_setting_add(root, "version", CONFIG_TYPE_INT); config_setting_set_int(setting, FORCE_OVERRIDE_VERSION); config_set_options(&_config, (CONFIG_OPTION_SEMICOLON_SEPARATORS | CONFIG_OPTION_COLON_ASSIGNMENT_FOR_GROUPS | CONFIG_OPTION_OPEN_BRACE_ON_SEPARATE_LINE)); config_write_file(&_config, CONFIG_FILE_NAME); // default values videoBitRate = 120000; videoGOP = 18; videoMaxBFrames = 2; audioBitRate = 48000; waitForSync = true; lastUsingServer = -1; } void ConfigManager::loadConfigFile() { config_setting_t *root, *setting; root = config_root_setting(&_config); setting = config_lookup(&_config, "servers"); if (setting != NULL) { printf("> Load server profiles\n"); int count = config_setting_length(setting), i = 0; for(i = 0; i < count; ++i) { config_setting_t* serverCfg = config_setting_get_elem(setting, i); ServerConfig server{}; const char* ip, * port, *name; if(!(config_setting_lookup_string(serverCfg, "ip", &ip) && config_setting_lookup_string(serverCfg, "port", &port) && config_setting_lookup_string(serverCfg, "name", &name))) { continue; } server.name = std::string(name); server.ip = std::string(ip); server.port = std::string(port); servers.push_back(server); } } if (!config_lookup_int(&_config, "last_using_server", &lastUsingServer)) lastUsingServer = -1; // video if (!config_lookup_int(&_config, "video_bit_rate", &videoBitRate)) videoBitRate = 120000; if (!config_lookup_int(&_config, "video_gop", &videoGOP)) videoGOP = 18; if (!config_lookup_int(&_config, "video_max_b_frames", &videoMaxBFrames)) videoMaxBFrames = 2; // audio if (!config_lookup_int(&_config, "audio_bit_rate", &audioBitRate)) audioBitRate = 48000; // mode int waitForReceived = 0; if (!config_lookup_bool(&_config, "wait_for_sync", &waitForReceived)) { waitForSync = true; } else waitForSync = waitForReceived; } void ConfigManager::InitConfig() { config_init(&_config); config_set_options(&_config, (CONFIG_OPTION_SEMICOLON_SEPARATORS | CONFIG_OPTION_COLON_ASSIGNMENT_FOR_GROUPS | CONFIG_OPTION_OPEN_BRACE_ON_SEPARATE_LINE)); printf("----------------------\nInitialize Config\n----------------------\n"); if(shouldCreateNewConfigFile()) { printf("> Create new config file\n"); createNewConfigFile(); }else { printf("> Load config file\n"); loadConfigFile(); } } void ConfigManager::Save() { config_setting_t *root, *setting, *element; root = config_root_setting(&_config); // reset server list setting = config_lookup(&_config, "servers"); if (setting != NULL) { int profileCount = config_setting_length(setting); while (profileCount >= 0) { int ret = config_setting_remove_elem(setting, 0); if (ret != CONFIG_TRUE) { printf("> Failed to detele profile at: %d\n", profileCount); } --profileCount; } } for (auto& i : servers) { config_setting_t* server = config_setting_add(setting, NULL, CONFIG_TYPE_GROUP); if(server != nullptr) { printf("> Profile: %s %s:%s.\n", i.name.c_str(), i.ip.c_str(), i.port.c_str()); element = config_setting_add(server, "ip", CONFIG_TYPE_STRING); config_setting_set_string(element, i.ip.c_str()); element = config_setting_add(server, "port", CONFIG_TYPE_STRING); config_setting_set_string(element, i.port.c_str()); element = config_setting_add(server, "name", CONFIG_TYPE_STRING); config_setting_set_string(element, i.name.c_str()); } } setting = config_setting_get_member(root, "last_using_server"); if (!setting) setting = config_setting_add(root, "last_using_server", CONFIG_TYPE_INT); config_setting_set_int(setting, lastUsingServer); printf("> Write video config.\n"); // video setting = config_setting_get_member(root, "video_bit_rate"); if (!setting) setting = config_setting_add(root, "video_bit_rate", CONFIG_TYPE_INT); config_setting_set_int(setting, videoBitRate); setting = config_setting_get_member(root, "video_gop"); if (!setting) setting = config_setting_add(root, "video_gop", CONFIG_TYPE_INT); config_setting_set_int(setting, videoGOP); setting = config_setting_get_member(root, "video_max_b_frames"); if (!setting) setting = config_setting_add(root, "video_max_b_frames", CONFIG_TYPE_INT); config_setting_set_int(setting, videoMaxBFrames); printf("> Write audio config.\n"); // audio setting = config_setting_get_member(root, "audio_bit_rate"); if (!setting) setting = config_setting_add(root, "audio_bit_rate", CONFIG_TYPE_INT); config_setting_set_int(setting, audioBitRate); // mode setting = config_setting_get_member(root, "wait_for_sync"); if (!setting) setting = config_setting_add(root, "wait_for_sync", CONFIG_TYPE_BOOL); config_setting_set_bool(setting, waitForSync); setting = config_setting_get_member(root, "version"); if (!setting) setting = config_setting_add(root, "version", CONFIG_TYPE_INT); config_setting_set_int(setting, FORCE_OVERRIDE_VERSION); // write file int ret = config_write_file(&_config, CONFIG_FILE_NAME); printf("> Save result: %d\n", ret); } void ConfigManager::Destroy() { config_destroy(&_config); } ================================================ FILE: PinBox/PinBox/source/Mutex.cpp ================================================ #include "Mutex.h" Mutex::Mutex() { _isLocked = false; LightLock_Init(&_handler); } Mutex::~Mutex() { if(_isLocked) LightLock_Unlock(&_handler); } void Mutex::Lock() { LightLock_Lock(&_handler); } void Mutex::TryLock() { if(!LightLock_TryLock(&_handler)) _isLocked = true; } void Mutex::Unlock() { LightLock_Unlock(&_handler); _isLocked = false; } ================================================ FILE: PinBox/PinBox/source/PPAudio.cpp ================================================ #include "PPAudio.h" #include #include #define SAMPLERATE 22050 #define SAMPLESPERBUF 1152 #define BYTESPERSAMPLE 4 /* Channel to play audio on */ #define CHANNEL 0x00 //--------------------------------------------------------------------- static PPAudio* mInstance = nullptr; PPAudio* PPAudio::Get() { if (mInstance == nullptr) { mInstance = new PPAudio(); } return mInstance; } void PPAudio::AudioInit() { if (_initialized) return; ndspInit(); // buf temporary u8 * temp = (u8 *)linearAlloc(SAMPLESPERBUF * BYTESPERSAMPLE * MAX_AUDIO_BUF); // fail to alloc tmp memory if(temp == nullptr) { ndspExit(); return; } memset(temp, 0, SAMPLESPERBUF * BYTESPERSAMPLE * MAX_AUDIO_BUF); DSP_FlushDataCache(temp, SAMPLESPERBUF * BYTESPERSAMPLE * MAX_AUDIO_BUF); ndspChnWaveBufClear(CHANNEL); ndspChnReset(CHANNEL); ndspSetOutputMode(NDSP_OUTPUT_STEREO); ndspChnSetInterp(CHANNEL, NDSP_INTERP_POLYPHASE); ndspChnSetRate(CHANNEL, SAMPLERATE); ndspChnSetFormat(CHANNEL, NDSP_FORMAT_STEREO_PCM16); // set mix float mix[12]; memset(mix, 0, sizeof(mix)); mix[0] = 1.0; mix[1] = 1.0; ndspChnSetMix(0, mix); memset(_waveBuf, 0, sizeof(_waveBuf)); _waveBuf[0].data_vaddr = temp; _waveBuf[0].nsamples = SAMPLESPERBUF; _waveBuf[0].status = NDSP_WBUF_DONE; _waveBuf[1].data_vaddr = temp + (SAMPLESPERBUF * BYTESPERSAMPLE); _waveBuf[1].nsamples = SAMPLESPERBUF; _waveBuf[1].status = NDSP_WBUF_DONE; _initialized = true; } void PPAudio::AudioExit() { if (!_initialized) return; _initialized = false; ndspChnWaveBufClear(CHANNEL); ndspExit(); linearFree(_waveBuf[0].data_vaddr); _waveBuf[0].data_vaddr = NULL; } void PPAudio::FillBuffer(u8* buffer, u32 size) { if (!_initialized) return; size_t nextBuf = _nextBuf; while (_waveBuf[nextBuf].status != NDSP_WBUF_DONE) { svcSleepThread(25* 1000ULL); } memcpy(_waveBuf[nextBuf].data_pcm16, buffer, SAMPLESPERBUF * BYTESPERSAMPLE); DSP_FlushDataCache(_waveBuf[nextBuf].data_pcm16, SAMPLESPERBUF * BYTESPERSAMPLE); _waveBuf[nextBuf].offset = 0; _waveBuf[nextBuf].status = NDSP_WBUF_QUEUED; ndspChnWaveBufAdd(CHANNEL, &_waveBuf[nextBuf]); _nextBuf = (nextBuf + 1) % MAX_AUDIO_BUF; } ================================================ FILE: PinBox/PinBox/source/PPDecoder.cpp ================================================ #include "PPDecoder.h" #include "PPAudio.h" static u8* pRGBBuffer = nullptr; volatile bool initialized = false; PPDecoder::PPDecoder() { } PPDecoder::~PPDecoder() { } void PPDecoder::initDecoder() { if (initialized) return; initialized = true; av_log_set_level(AV_LOG_QUIET); av_register_all(); //----------------------------------------------------------------- // init video encoder //----------------------------------------------------------------- const AVCodec* videoCodec = avcodec_find_decoder(AV_CODEC_ID_MPEG4); pVideoContext = avcodec_alloc_context3(videoCodec); pVideoContext->width = 400; pVideoContext->height = 240; pVideoContext->pix_fmt = AV_PIX_FMT_YUV420P; pVideoContext->thread_count = 4; pVideoContext->thread_type = FF_THREAD_FRAME; // Open int ret = avcodec_open2(pVideoContext, videoCodec, NULL); if (ret < 0) { printf("failed to open Video decoder: %d\n", ret); } pVideoPacket = av_packet_alloc(); pVideoFrame = av_frame_alloc(); initY2RImageConverter(); //----------------------------------------------------------------- // init audio encoder //----------------------------------------------------------------- const AVCodec *audioCodec = avcodec_find_decoder(AV_CODEC_ID_MP2); if(!audioCodec) { printf("[Audio] Codec not found!\n"); } pAudioContext = avcodec_alloc_context3(audioCodec); pAudioContext->bit_rate = 64000; pAudioContext->sample_fmt = AV_SAMPLE_FMT_S16; pAudioContext->request_sample_fmt = AV_SAMPLE_FMT_S16; pAudioContext->request_channel_layout = AV_CH_LAYOUT_STEREO; pAudioContext->sample_rate = 22050; pAudioContext->channels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);; pAudioContext->channel_layout = AV_CH_LAYOUT_STEREO; ret = avcodec_open2(pAudioContext, audioCodec, NULL); if(ret < 0) { printf("[Audio] Failed to open context: %d\n", ret); } pAudioPacket = av_packet_alloc(); pAudioFrame = av_frame_alloc(); } void PPDecoder::releaseDecoder() { if (!initialized) return; initialized = false; printf("Release audio/video decoder.\n"); // free video avcodec_free_context(&pVideoContext); av_frame_free(&pVideoFrame); av_packet_free(&pVideoPacket); // free audio avcodec_free_context(&pAudioContext); av_frame_free(&pAudioFrame); av_packet_free(&pAudioPacket); //--------------------------------------------------- bool is_busy = 0; Y2RU_StopConversion(); Y2RU_IsBusyConversion(&is_busy); y2rExit(); linearFree(pRGBBuffer); } u8* PPDecoder::appendVideoBuffer(u8* buffer, u32 size) { if (!initialized) return nullptr; if (size <= 0) return nullptr; pVideoPacket->data = buffer; pVideoPacket->size = size; return decodeVideoStream(); } void PPDecoder::initY2RImageConverter() { //-------------------------------------------------------------------------------------- // NOTE: code borrow from 3DS video player // ref: https://github.com/Lectem/3Damnesic/blob/master/source/color_converter.c //-------------------------------------------------------------------------------------- pDecodeState = new DecodeState(); Result res = 0; res = y2rInit(); if (res != 0) printf("Error when init Y2R\n"); res = Y2RU_StopConversion(); if (res != 0) printf("Error on Y2RU_StopConversion\n"); bool is_busy = 0; int tries = 0; do { svcSleepThread(25 * 1000ull); res = Y2RU_StopConversion(); if (res != 0) printf("Error on Y2RU_StopConversion\n"); res = Y2RU_IsBusyConversion(&is_busy); if (res != 0) printf("Error on Y2RU_IsBusyConversion\n"); tries += 1; } while (is_busy && tries < 100); pDecodeState->y2rParams.input_format = INPUT_YUV420_INDIV_8; pDecodeState->y2rParams.output_format = OUTPUT_RGB_24; pDecodeState->y2rParams.rotation = ROTATION_NONE; pDecodeState->y2rParams.block_alignment = BLOCK_8_BY_8; pDecodeState->y2rParams.input_line_width = 400; pDecodeState->y2rParams.input_lines = 240; if (pDecodeState->y2rParams.input_lines % 8) { pDecodeState->y2rParams.input_lines += 8 - (pDecodeState->y2rParams.input_lines % 8); } pDecodeState->y2rParams.standard_coefficient = COEFFICIENT_ITU_R_BT_601; pDecodeState->y2rParams.unused = 0; pDecodeState->y2rParams.alpha = 0xFF; res = Y2RU_SetConversionParams(&pDecodeState->y2rParams); if (res != 0) printf("Error on Y2RU_SetConversionParams\n"); res = Y2RU_SetTransferEndInterrupt(true); if (res != 0) printf("Error on Y2RU_SetTransferEndInterrupt\n"); pDecodeState->endEvent = 0; res = Y2RU_GetTransferEndEvent(&pDecodeState->endEvent); if (res != 0) printf("Error on Y2RU_GetTransferEndEvent\n"); } void PPDecoder::convertColor() { Result res; const s16 img_w = pDecodeState->y2rParams.input_line_width; const s16 img_h = pDecodeState->y2rParams.input_lines; const u32 img_size = img_w * img_h; const u32 img_w_UV = img_w >> 1; size_t src_Y_size = 0; size_t src_UV_size = 0; switch (pDecodeState->y2rParams.input_format) { case INPUT_YUV422_INDIV_8: src_Y_size = img_size; src_UV_size = img_size / 2; break; case INPUT_YUV420_INDIV_8: src_Y_size = img_size; src_UV_size = img_size / 4; break; case INPUT_YUV422_INDIV_16: src_Y_size = img_size * 2; src_UV_size = img_size / 2 * 2; break; case INPUT_YUV420_INDIV_16: src_Y_size = img_size * 2; src_UV_size = img_size / 4 * 2; break; case INPUT_YUV422_BATCH: src_Y_size = img_size * 2; src_UV_size = img_size * 2; break; } u8 *src_Y = (u8*)pVideoFrame->data[0]; u8 *src_U = (u8*)pVideoFrame->data[1]; u8 *src_V = (u8*)pVideoFrame->data[2]; const s16 src_Y_padding = pVideoFrame->linesize[0] - img_w; const s16 src_UV_padding = pVideoFrame->linesize[1] - img_w_UV; Y2RU_StopConversion(); res = Y2RU_SetSendingY(src_Y, src_Y_size, img_w, src_Y_padding); if (res != 0) printf("Error on Y2RU_SetSendingY\n"); res = Y2RU_SetSendingU(src_U, src_UV_size, img_w_UV, src_UV_padding); if (res != 0) printf("Error on Y2RU_SetSendingU\n"); res = Y2RU_SetSendingV(src_V, src_UV_size, img_w_UV, src_UV_padding); if (res != 0) printf("Error on Y2RU_SetSendingV\n"); const u16 pixSize = 3; size_t rgb_size = (512*256) * pixSize; s16 transfer_unit = 8; s16 gap = (512 - img_w) * transfer_unit * pixSize; //TODO: try this with get frame buffer res = Y2RU_SetReceiving(pRGBBuffer, rgb_size, img_w * transfer_unit * pixSize, gap); if (res != 0) printf("Error on Y2RU_SetReceiving\n"); res = Y2RU_StartConversion(); if (res != 0) printf("Error on Y2RU_StartConversion\n"); res = svcWaitSynchronization(pDecodeState->endEvent, 1000000000ull); if (res != 0) printf("Error on svcWaitSynchronization\n"); } u8* PPDecoder::decodeVideoStream() { int ret = 0; ret = avcodec_send_packet(pVideoContext, pVideoPacket); if (ret < 0) return nullptr; ret = avcodec_receive_frame(pVideoContext, pVideoFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return nullptr; if (ret < 0) return nullptr; //---------------------------------------------- // decode video frame //---------------------------------------------- iFrameWidth = pVideoFrame->width; iFrameHeight =pVideoFrame->height; if (pRGBBuffer == nullptr) pRGBBuffer = (u8*)linearMemAlign(3 * 512 * 256, 0x80); convertColor(); av_packet_unref(pVideoPacket); return pRGBBuffer; } void PPDecoder::decodeAudioStream(u8* buffer, u32 size) { if (!initialized) return; if (size == 0) return; int ret = 0; av_packet_unref(pVideoPacket); pAudioPacket->data = buffer; pAudioPacket->size = size; ret = avcodec_send_packet(pAudioContext, pAudioPacket); if (ret < 0) { printf("[Audio] Error submitting the packet to the decoder: %d\n", ret); } else { while (ret >= 0) { ret = avcodec_receive_frame(pAudioContext, pAudioFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; if (ret < 0) { printf("[Audio] get frame failed: %d\n", ret); return; } PPAudio::Get()->FillBuffer(pAudioFrame->extended_data[0], pAudioFrame->linesize[0]); } } } ================================================ FILE: PinBox/PinBox/source/PPGraphics.cpp ================================================ #include "PPGraphics.h" #include "vshader_shbin.h" #include #include #include <3ds/gpu/enums.h> #include <3ds/gfx.h> #include #include #include <3ds/gpu/gx.h> #include <3ds/allocator/linear.h> #include <3ds/gpu/shaderProgram.h> #include #include <3ds/font.h> #include <3ds/util/utf.h> #include "lodepng.h" #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) //--------------------------------------------------------------------- // Graphics Instance //--------------------------------------------------------------------- static PPGraphics* mInstance = nullptr; static Vector2 mCircleVertex12[12]; #define TEX_MIN_SIZE 32 //Grabbed from: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 unsigned int next_pow2(unsigned int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v >= TEX_MIN_SIZE ? v : TEX_MIN_SIZE; } PPGraphics* PPGraphics::Get() { if(mInstance == nullptr) { mInstance = new PPGraphics(); } return mInstance; } void PPGraphics::GraphicsInit() { // shared data int arrSize = IM_ARRAYSIZE(mCircleVertex12); for(int i = 0; i < arrSize; ++i) { const float a = ((float)i * 2 * M_PI) / (float)IM_ARRAYSIZE(mCircleVertex12); mCircleVertex12[i] = Vector2{ cosf(a), sinf(a) }; } // init gfxInitDefault(); C3D_Init(C3D_DEFAULT_CMDBUF_SIZE); //--------------------------------------------------------------------- // Setup render target //--------------------------------------------------------------------- mRenderTargetTop = C3D_RenderTargetCreate(240, 400, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); C3D_RenderTargetClear(mRenderTargetTop, C3D_CLEAR_ALL, CLEAR_COLOR, 0); C3D_RenderTargetSetOutput(mRenderTargetTop, GFX_TOP, GFX_LEFT, DISPLAY_TRANSFER_FLAGS); mRenderTargetBtm = C3D_RenderTargetCreate(240, 320, GPU_RB_RGBA8, GPU_RB_DEPTH24_STENCIL8); C3D_RenderTargetClear(mRenderTargetBtm, C3D_CLEAR_ALL, CLEAR_COLOR, 0); C3D_RenderTargetSetOutput(mRenderTargetBtm, GFX_BOTTOM, GFX_LEFT, DISPLAY_TRANSFER_FLAGS); //--------------------------------------------------------------------- // Setup top screen sprite ( for video render ) //--------------------------------------------------------------------- mTopScreenSprite = new Sprite(); //--------------------------------------------------------------------- // Init memory pool // @Code borrow from libsf2d //--------------------------------------------------------------------- memoryPoolAddr = linearAlloc(0x80000); memoryPoolSize = 0x80000; //--------------------------------------------------------------------- // Load the vertex shader, create a shader program and bind it //--------------------------------------------------------------------- mVShaderDVLB = DVLB_ParseFile((u32*)vshader_shbin, vshader_shbin_size); shaderProgramInit(&mShaderProgram); shaderProgramSetVsh(&mShaderProgram, &mVShaderDVLB->DVLE[0]); C3D_BindProgram(&mShaderProgram); mULocProjection = shaderInstanceGetUniformLocation(mShaderProgram.vertexShader, "projection"); Mtx_OrthoTilt(&mProjectionTop, 0.0, 400, 240, 0.0, 0.0, 1.0, true); Mtx_OrthoTilt(&mProjectionBtm, 0.0, 320, 240, 0.0, 0.0, 1.0, true); C3D_CullFace(GPU_CULL_NONE); C3D_DepthTest(true, GPU_GEQUAL, GPU_WRITE_ALL); //--------------------------------------------------------------------- // Init top screen sprite //--------------------------------------------------------------------- mTopScreenSprite->initialized = true; C3D_TexInit(&mTopScreenSprite->tex, 512, 256, GPU_RGB8); C3D_TexSetFilter(&mTopScreenSprite->tex, GPU_LINEAR, GPU_NEAREST); C3D_TexSetWrap(&mTopScreenSprite->tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER); //--------------------------------------------------------------------- // System font init //--------------------------------------------------------------------- Result res = fontEnsureMapped(); int i; TGLP_s* glyphInfo = fontGetGlyphInfo(); mGlyphSheets = malloc(sizeof(C3D_Tex)*glyphInfo->nSheets); for (i = 0; i < glyphInfo->nSheets; i++) { C3D_Tex* tex = &mGlyphSheets[i]; tex->data = fontGetGlyphSheetTex(i); tex->fmt = glyphInfo->sheetFmt; tex->size = glyphInfo->sheetSize; tex->width = glyphInfo->sheetWidth; tex->height = glyphInfo->sheetHeight; tex->param = GPU_TEXTURE_MAG_FILTER(GPU_LINEAR) | GPU_TEXTURE_MIN_FILTER(GPU_LINEAR) | GPU_TEXTURE_WRAP_S(GPU_CLAMP_TO_EDGE) | GPU_TEXTURE_WRAP_T(GPU_CLAMP_TO_EDGE); tex->border = 0; tex->lodParam = 0; } } void PPGraphics::GraphicExit() { // clean up cache for(auto it = mTexCached.begin(); it != mTexCached.end(); ++it) { if(it->second->initialized) C3D_TexDelete(&it->second->tex); delete it->second; } mTexCached.clear(); // delete top if(mTopScreenSprite->initialized) C3D_TexDelete(&mTopScreenSprite->tex); delete mTopScreenSprite; linearFree(memoryPoolAddr); free(mGlyphSheets); shaderProgramFree(&mShaderProgram); DVLB_Free(mVShaderDVLB); C3D_Fini(); gfxExit(); } Sprite* PPGraphics::AddCacheImageAsset(const char* name, std::string key) { auto iter = mTexCached.find(key); if (iter != mTexCached.end()) { return iter->second; } // get image path char path[100]; sprintf(path, "romfs:/assets/%s", name); return AddCacheImage(path, key); } Sprite* PPGraphics::AddCacheImage(const char* path, std::string key) { auto iter = mTexCached.find(key); if (iter != mTexCached.end()) { return iter->second; } unsigned char* image; unsigned width, height; int ret = lodepng_decode32_file(&image, &width, &height, path); if (ret != 0) { printf("Failed when decode asset image: %s with key: %s\n", path, key.c_str()); return nullptr; } u8 *gpusrc = linearAlloc(width*height * 4); u8* src = image; u8 *dst = gpusrc; // lodepng outputs big endian rgba so we need to convert for (int i = 0; itex, next_pow2(width), next_pow2(height), GPU_RGBA8); if (!success) { free(sprite); return nullptr; } sprite->width = width; sprite->height = height; C3D_TexSetWrap(&sprite->tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER); printf("Added sprite: %s from path: %s\n", key.c_str(), path); GSPGPU_FlushDataCache(gpusrc, width*height * 4); C3D_SyncDisplayTransfer((u32*)gpusrc, GX_BUFFER_DIM(width, height), (u32*)sprite->tex.data, GX_BUFFER_DIM(sprite->tex.width, sprite->tex.height), TEXTURE_RGBA_TRANSFER_FLAGS); free(image); linearFree(gpusrc); mTexCached[key] = sprite; return sprite; } Sprite* PPGraphics::AddCacheImage(u8* buf, u32 size, std::string key) { auto iter = mTexCached.find(key); if (iter != mTexCached.end()) { return iter->second; } // load data unsigned char* image; unsigned width, height; int ret = lodepng_decode32(&image, &width, &height, buf, size); if(ret != 0) { printf("Failed when decode png image with key: %s\n", key.c_str()); return nullptr; } u8 *gpusrc = linearAlloc(width*height * 4); u8* src = image; u8 *dst = gpusrc; // lodepng outputs big endian rgba so we need to convert for (int i = 0; itex, next_pow2(width), next_pow2(height), GPU_RGBA8); if(!success) { delete sprite; return nullptr; } sprite->width = width; sprite->height = height; C3D_TexSetWrap(&sprite->tex, GPU_CLAMP_TO_BORDER, GPU_CLAMP_TO_BORDER); printf("added key: %s - size: %d\n", key.c_str(), size); GSPGPU_FlushDataCache(gpusrc, width*height * 4); C3D_SyncDisplayTransfer((u32*)gpusrc, GX_BUFFER_DIM(width, height), (u32*)sprite->tex.data, GX_BUFFER_DIM(sprite->tex.width, sprite->tex.height), TEXTURE_RGBA_TRANSFER_FLAGS); free(image); linearFree(gpusrc); mTexCached[key] = sprite; return sprite; } Sprite* PPGraphics::GetCacheImage(std::string key) { auto iter = mTexCached.find(key); if (iter != mTexCached.end()) { return iter->second; } printf("Image cache not found: %s\n", key.c_str()); return nullptr; } PPGraphics::~PPGraphics() { } void PPGraphics::BeginRender() { resetMemoryPool(); C3D_FrameBegin(C3D_FRAME_SYNCDRAW); } void PPGraphics::RenderOn(gfxScreen_t screen) { mCurrentDrawScreen = screen; if (screen == GFX_TOP) { C3D_FrameDrawOn(mRenderTargetTop); // set uniform projection C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, mULocProjection, &mProjectionTop); // draw a transparent and small dot to avoid soft lock // @ref : https://github.com/fincs/citro3d/issues/35 DrawRectangle(0, 0, 1, 1, Color{ 0,0,0,255 }); } else { C3D_FrameDrawOn(mRenderTargetBtm); // set uniform projection C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, mULocProjection, &mProjectionBtm); // draw a transparent and small dot to avoid soft lock // @ref : https://github.com/fincs/citro3d/issues/35 DrawRectangle(0, 0, 1, 1, Color{ 0,0,0,255 }); } } void PPGraphics::EndRender() { C3D_FrameEnd(0); } void PPGraphics::UpdateTopScreenSprite(u8* data, u32 size) { if (!mTopScreenSprite->initialized) return; memcpy(mTopScreenSprite->tex.data, data, size); GSPGPU_FlushDataCache(mTopScreenSprite->tex.data, size); } void PPGraphics::DrawTopScreenSprite() { if (!mTopScreenSprite->initialized) return; float x = 0, y = 0, w = 400.0f, h = 240.0f; float ow = 512.0f, oh = 256.0f; float u = 1; float v = 1; VertexPosTex *vertices = (VertexPosTex*)allocMemoryPoolAligned(sizeof(VertexPosTex) * 4, 8); // set position vertices[0].position = (Vector3) { 0, 0, 0.5f }; vertices[1].position = (Vector3) { 512.0f, 0, 0.5f }; vertices[2].position = (Vector3) { 0, 256.0f, 0.5f }; vertices[3].position = (Vector3) { 512.0f, 256.0f, 0.5f }; vertices[0].textcoord = (Vector2) { 0.0f, 1.0f }; vertices[1].textcoord = (Vector2) { 1.0f, 1.0f}; vertices[2].textcoord = (Vector2) { 0.0f, 0.0f }; vertices[3].textcoord = (Vector2) { 1.0f, 0.0f}; // setup env C3D_TexBind(getTextUnit(GPU_TEXUNIT0), &mTopScreenSprite->tex); C3D_TexEnv* env = C3D_GetTexEnv(0); C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0, 0, 0); C3D_TexEnvOp(env, C3D_Both, 0, 0, 0); C3D_TexEnvFunc(env, C3D_Both, GPU_REPLACE); C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, vertices, sizeof(VertexPosTex), 2, 0x10); C3D_DrawArrays(GPU_TRIANGLE_STRIP, 0, 4); } void PPGraphics::setupForPosCollEnv(void* vertices) { C3D_TexEnv* env = C3D_GetTexEnv(0); C3D_TexEnvSrc(env, C3D_Both, GPU_PRIMARY_COLOR, 0, 0); C3D_TexEnvOp(env, C3D_Both, 0, 0, 0); C3D_TexEnvFunc(env, C3D_Both, GPU_REPLACE); C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); AttrInfo_AddLoader(attrInfo, 1, GPU_UNSIGNED_BYTE, 4); C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, vertices, sizeof(VertexPosCol), 2, 0x10); } void PPGraphics::setupForPosTexlEnv(void* vertices, u32 color, int texID) { C3D_TexEnv* env = C3D_GetTexEnv(0); C3D_TexEnvSrc(env, C3D_RGB, GPU_CONSTANT, 0, 0); C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0, GPU_CONSTANT, 0); C3D_TexEnvOp(env, C3D_Both, 0, 0, 0); C3D_TexEnvFunc(env, C3D_RGB, GPU_REPLACE); C3D_TexEnvFunc(env, C3D_Alpha, GPU_MODULATE); C3D_TexEnvColor(env, color); C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, vertices, sizeof(VertexPosTex), 2, 0x10); } int PPGraphics::getTextUnit(GPU_TEXUNIT unit) { switch (unit) { case GPU_TEXUNIT0: return 0; case GPU_TEXUNIT1: return 1; case GPU_TEXUNIT2: return 2; default: return -1; } } void* PPGraphics::allocMemoryPoolAligned(u32 size, u32 alignment) { u32 new_index = (memoryPoolIndex + alignment - 1) & ~(alignment - 1); if ((new_index + size) < memoryPoolSize) { void *addr = (void *)((u32)memoryPoolAddr + new_index); memoryPoolIndex = new_index + size; return addr; } return NULL; } void PPGraphics::DrawImage(Sprite* sprite, int x, int y) { DrawImage(sprite, x, y, sprite->width, sprite->height); } void PPGraphics::DrawImage(Sprite* sprite, int x, int y, int w, int h) { DrawImage(sprite, x, y, w, h, 0); } void PPGraphics::DrawImage(Sprite* sprite, int x, int y, int w, int h, int degrees) { DrawImage(sprite, x, y, w, h, degrees, Vector2{ 0.5f, 0.5f }); } void PPGraphics::DrawImage(Sprite* sprite, int x, int y, int w, int h, int degrees, Vector2 anchor) { if (!sprite) return; C3D_TexFlush(&sprite->tex); // bind texture C3D_TexBind(getTextUnit(GPU_TEXUNIT0), &sprite->tex); C3D_TexEnv* env = C3D_GetTexEnv(0); C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0, 0, 0); C3D_TexEnvOp(env, C3D_Both, 0, 0, 0); C3D_TexEnvFunc(env, C3D_Both, GPU_REPLACE); VertexPosTex *vertices = (VertexPosTex*)allocMemoryPoolAligned(sizeof(VertexPosTex) * 4, 8); if (!vertices) return; // set position vertices[0].position = (Vector3) { x, y, 0.5f }; vertices[1].position = (Vector3) { w + x, y, 0.5f }; vertices[2].position = (Vector3) { x, h + y, 0.5f }; vertices[3].position = (Vector3) { w + x, h + y, 0.5f }; float u = sprite->width / (float)sprite->tex.width; float v = sprite->width / (float)sprite->tex.height; // set uv vertices[0].textcoord = (Vector2) { 0.0f, 0.0f }; vertices[1].textcoord = (Vector2) { u, 0.0f }; vertices[2].textcoord = (Vector2) { 0.0f, v }; vertices[3].textcoord = (Vector2) { u, v }; // rotate if need if (degrees != 0) { float rad = (float)degrees * M_PI / 180.f; const float c = cosf(rad); const float s = sinf(rad); float cx = x + w * anchor.x; float cy = y + h * anchor.y; int i; for (i = 0; i < 4; ++i) { // Rotate and translate float _x = cx - vertices[i].position.x; float _y = cy - vertices[i].position.y; vertices[i].position.x = _x*c - _y*s + cx; vertices[i].position.y = _x*s + _y*c + cy; } } // setup attributes C3D_AttrInfo* attrInfo = C3D_GetAttrInfo(); AttrInfo_Init(attrInfo); AttrInfo_AddLoader(attrInfo, 0, GPU_FLOAT, 3); AttrInfo_AddLoader(attrInfo, 1, GPU_FLOAT, 2); C3D_BufInfo* bufInfo = C3D_GetBufInfo(); BufInfo_Init(bufInfo); BufInfo_Add(bufInfo, vertices, sizeof(VertexPosTex), 2, 0x10); C3D_DrawArrays(GPU_TRIANGLE_STRIP, 0, 4); } void PPGraphics::DrawRectangle(float x, float y, float w, float h, Color color, float rounding) { u32 col = color.toU32(); if(rounding > 0.0f) { VertexPosCol* vertices = (VertexPosCol*)allocMemoryPoolAligned(sizeof(VertexPosCol) * 66, 8); if (!vertices) return; int vIndex = -1; Vector3 outters[8]; int outterIdx = -1; Vector3 tl = Vector3{ x + rounding, y + rounding, 0.5f }; Vector3 tr = Vector3{ x + w - rounding, y + rounding, 0.5f }; Vector3 bl = Vector3{ x + rounding, y + h - rounding, 0.5f }; Vector3 br = Vector3{ x + w - rounding, y + h - rounding, 0.5f }; // main rect vertices[++vIndex] = VertexPosCol { tl , col }; // top-left vertices[++vIndex] = VertexPosCol { tr , col }; // top-right vertices[++vIndex] = VertexPosCol { bl , col }; // bottom-left vertices[++vIndex] = VertexPosCol { tr , col }; // top-right vertices[++vIndex] = VertexPosCol { bl , col }; // bottom-left vertices[++vIndex] = VertexPosCol { br , col }; // bottom-right // arc path func // tl : 6, 9 tr : 9, 12 br : 0, 3 bl : 3, 6 const std::function arcVertices = [&](Vector3 center, int min, int max) { Vector3 result[4]; int i = -1; for (int a = min; a <= max; ++a) { const Vector2& v = mCircleVertex12[a % IM_ARRAYSIZE(mCircleVertex12)]; result[++i] = Vector3{ center.x + v.x * rounding, center.y + v.y * rounding, 0.5f }; } // add vertices vertices[++vIndex] = VertexPosCol{ center , col }; vertices[++vIndex] = VertexPosCol{ result[0] , col }; vertices[++vIndex] = VertexPosCol{ result[1] , col }; vertices[++vIndex] = VertexPosCol{ center , col }; vertices[++vIndex] = VertexPosCol{ result[1] , col }; vertices[++vIndex] = VertexPosCol{ result[2] , col }; vertices[++vIndex] = VertexPosCol{ center , col }; vertices[++vIndex] = VertexPosCol{ result[2] , col }; vertices[++vIndex] = VertexPosCol{ result[3] , col }; outters[++outterIdx] = result[0]; outters[++outterIdx] = result[3]; }; arcVertices(tl, 6, 9); arcVertices(tr, 9, 12); arcVertices(br, 0, 3); arcVertices(bl, 3, 6); // outer rect vertices[++vIndex] = VertexPosCol{ tl , col }; vertices[++vIndex] = VertexPosCol{ tr , col }; vertices[++vIndex] = VertexPosCol{ outters[1] , col }; vertices[++vIndex] = VertexPosCol{ tr , col }; vertices[++vIndex] = VertexPosCol{ outters[1] , col }; vertices[++vIndex] = VertexPosCol{ outters[2] , col }; vertices[++vIndex] = VertexPosCol{ tr , col }; vertices[++vIndex] = VertexPosCol{ br , col }; vertices[++vIndex] = VertexPosCol{ outters[3] , col }; vertices[++vIndex] = VertexPosCol{ outters[3] , col }; vertices[++vIndex] = VertexPosCol{ br , col }; vertices[++vIndex] = VertexPosCol{ outters[4] , col }; vertices[++vIndex] = VertexPosCol{ bl , col }; vertices[++vIndex] = VertexPosCol{ br , col }; vertices[++vIndex] = VertexPosCol{ outters[5] , col }; vertices[++vIndex] = VertexPosCol{ bl , col }; vertices[++vIndex] = VertexPosCol{ outters[5] , col }; vertices[++vIndex] = VertexPosCol{ outters[6] , col }; vertices[++vIndex] = VertexPosCol{ tl , col }; vertices[++vIndex] = VertexPosCol{ bl , col }; vertices[++vIndex] = VertexPosCol{ outters[0] , col }; vertices[++vIndex] = VertexPosCol{ bl , col }; vertices[++vIndex] = VertexPosCol{ outters[0] , col }; vertices[++vIndex] = VertexPosCol{ outters[7] , col }; setupForPosCollEnv(vertices); C3D_DrawArrays(GPU_TRIANGLES, 0, 66); }else { VertexPosCol* vertices = (VertexPosCol*)allocMemoryPoolAligned(sizeof(VertexPosCol) * 4, 8); if (!vertices) return; u32 vIndex = 0; vertices[vIndex] = VertexPosCol{ Vector3{ x, y, 0.5f } , col }; vertices[++vIndex] = VertexPosCol{ Vector3{ x + w, y, 0.5f } , col }; vertices[++vIndex] = VertexPosCol{ Vector3{ x, y + h, 0.5f } , col }; vertices[++vIndex] = VertexPosCol{ Vector3{ x + w, y + h, 0.5f } , col }; setupForPosCollEnv(vertices); C3D_DrawArrays(GPU_TRIANGLE_STRIP, 0, 4); } } void PPGraphics::StartMasked(float x, float y, float w, float h, gfxScreen_t screen) const { if(screen == GFX_TOP) C3D_SetScissor(GPU_SCISSOR_NORMAL, 240 - (y + h), 400 - (x + w), 240 - y, 400 - x); else C3D_SetScissor(GPU_SCISSOR_NORMAL, 240 - (y + h), 320 - (x + w), 240 - y, 320 - x); } void PPGraphics::StopMasked() const { C3D_SetScissor(GPU_SCISSOR_DISABLE, 0, 0, 0, 0); } void PPGraphics::DrawText(const char* text, float x, float y, float scaleX, float scaleY, Color color, bool baseline) { ssize_t units; u32 code; const u8* p = (const u8*)text; float firstX = x; u32 flags = GLYPH_POS_CALC_VTXCOORD | (baseline ? GLYPH_POS_AT_BASELINE : 0); int lastSheet = -1; do { if(!*p) break; units = decode_utf8(&code, p); if(units == -1) break; p += units; if( code == '\n') { x = firstX; y += scaleY * fontGetInfo()->lineFeed; }else if(code > 0) { int glyphIdx = fontGlyphIndexFromCodePoint(code); fontGlyphPos_s data; fontCalcGlyphPos(&data, glyphIdx, flags, scaleX, scaleY); // Bind the correct texture sheet if (data.sheetIndex != lastSheet) { lastSheet = data.sheetIndex; C3D_TexBind(getTextUnit(GPU_TEXUNIT0), &mGlyphSheets[lastSheet]); } VertexPosTex* vertices = (VertexPosTex*)allocMemoryPoolAligned(sizeof(VertexPosTex) * 4, 8); if (!vertices) break; // out of memory in pool // set position vertices[0].position = (Vector3) { x + data.vtxcoord.left, y + data.vtxcoord.bottom, 0.5f }; vertices[1].position = (Vector3) { x + data.vtxcoord.right, y + data.vtxcoord.bottom, 0.5f }; vertices[2].position = (Vector3) { x + data.vtxcoord.left, y + data.vtxcoord.top, 0.5f }; vertices[3].position = (Vector3) { x + data.vtxcoord.right, y + data.vtxcoord.top, 0.5f }; // set uv vertices[0].textcoord = (Vector2) { data.texcoord.left , data.texcoord.bottom }; vertices[1].textcoord = (Vector2) { data.texcoord.right, data.texcoord.bottom }; vertices[2].textcoord = (Vector2) { data.texcoord.left, data.texcoord.top }; vertices[3].textcoord = (Vector2) { data.texcoord.right, data.texcoord.top }; setupForPosTexlEnv(vertices, color.toU32(), TEX_FONT_GRAPHIC); C3D_DrawArrays(GPU_TRIANGLE_STRIP, 0, 4); x += data.xAdvance; } } while (code > 0); } void PPGraphics::DrawTextAutoWrap(const char* text, float x, float y, float w, float scaleX, float scaleY, Color color, bool baseline) { ssize_t units; u32 code; const u8* p = (const u8*)text; float firstX = x; u32 flags = GLYPH_POS_CALC_VTXCOORD | (baseline ? GLYPH_POS_AT_BASELINE : 0); int lastSheet = -1; do { if (!*p) break; units = decode_utf8(&code, p); if (units == -1) break; p += units; if (code == '\n') { x = firstX; y += scaleY * fontGetInfo()->lineFeed; } else if (code > 0) { int glyphIdx = fontGlyphIndexFromCodePoint(code); fontGlyphPos_s data; fontCalcGlyphPos(&data, glyphIdx, flags, scaleX, scaleY); // Bind the correct texture sheet if (data.sheetIndex != lastSheet) { lastSheet = data.sheetIndex; C3D_TexBind(getTextUnit(GPU_TEXUNIT0), &mGlyphSheets[lastSheet]); } VertexPosTex* vertices = (VertexPosTex*)allocMemoryPoolAligned(sizeof(VertexPosTex) * 4, 8); if (!vertices) break; // out of memory in pool // set position vertices[0].position = (Vector3) { x + data.vtxcoord.left, y + data.vtxcoord.bottom, 0.5f }; vertices[1].position = (Vector3) { x + data.vtxcoord.right, y + data.vtxcoord.bottom, 0.5f }; vertices[2].position = (Vector3) { x + data.vtxcoord.left, y + data.vtxcoord.top, 0.5f }; vertices[3].position = (Vector3) { x + data.vtxcoord.right, y + data.vtxcoord.top, 0.5f }; // set uv vertices[0].textcoord = (Vector2) { data.texcoord.left, data.texcoord.bottom }; vertices[1].textcoord = (Vector2) { data.texcoord.right, data.texcoord.bottom }; vertices[2].textcoord = (Vector2) { data.texcoord.left, data.texcoord.top }; vertices[3].textcoord = (Vector2) { data.texcoord.right, data.texcoord.top }; setupForPosTexlEnv(vertices, color.toU32(), TEX_FONT_GRAPHIC); C3D_DrawArrays(GPU_TRIANGLE_STRIP, 0, 4); // this line is seem to over if (x + data.width > w) { x = firstX; y += scaleY * fontGetInfo()->lineFeed; } else { x += data.xAdvance; } } } while (code > 0); } Vector2 PPGraphics::GetTextSize(const char* text, float scaleX, float scaleY) { ssize_t units; u32 code; Vector2 result; float maxW = 0, cW = 0; const u8* p = (const u8*)text; u32 flags = GLYPH_POS_CALC_VTXCOORD | 0; result.y = scaleY * fontGetInfo()->lineFeed; do { if (!*p) break; units = decode_utf8(&code, p); if (units == -1) break; p += units; if (code == '\n') { if(cW < maxW) cW = maxW; maxW = 0; result.y += scaleY * fontGetInfo()->lineFeed; }else if (code > 0) { int glyphIdx = fontGlyphIndexFromCodePoint(code); fontGlyphPos_s data; fontCalcGlyphPos(&data, glyphIdx, flags, scaleX, scaleY); maxW += data.xAdvance; } } while (code > 0); if (cW < maxW) cW = maxW; result.x = cW; return result; } Vector3 PPGraphics::GetTextSizeAutoWrap(const char* text, float scaleX, float scaleY, float w) { ssize_t units; u32 code; Vector3 result; float maxW = 0; float padding = 2; const u8* p = (const u8*)text; u32 flags = GLYPH_POS_CALC_VTXCOORD | 0; result.x = 0; result.z = 1; // lines result.y = scaleY * fontGetInfo()->lineFeed + padding; // height do { if (!*p) break; units = decode_utf8(&code, p); if (units == -1) break; p += units; if (code == '\n') { if (result.x < maxW) result.x = maxW; maxW = 0; result.y += scaleY * fontGetInfo()->lineFeed + padding; result.z += 1; } else if (code > 0) { int glyphIdx = fontGlyphIndexFromCodePoint(code); fontGlyphPos_s data; fontCalcGlyphPos(&data, glyphIdx, flags, scaleX, scaleY); if (maxW + data.width > w) { if (result.x < maxW) result.x = maxW; maxW = 0; result.y += scaleY * fontGetInfo()->lineFeed + padding; result.z += 1; } else maxW += data.xAdvance; } } while (code > 0); if (result.x < maxW) result.x = maxW; return result; } ================================================ FILE: PinBox/PinBox/source/PPMessage.cpp ================================================ #include "PPMessage.h" PPMessage::~PPMessage() { if (g_content != nullptr) free(g_content); } u8* PPMessage::BuildMessage(u8* contentBuffer, u32 contentSize) { g_contentSize = contentSize; //----------------------------------------------- // alloc msg buffer block u8* msgBuffer = (u8*)malloc(sizeof(u8) * (contentSize + 9)); //----------------------------------------------- // build header u8* pointer = msgBuffer; // 1, validate code WRITE_CHAR_PTR(pointer, g_validateCode, 4); // 2, message code WRITE_U8(pointer, g_code); // 3, content size WRITE_U32(pointer, g_contentSize); //----------------------------------------------- // build content data if (g_contentSize > 0) { memcpy(msgBuffer + 9, contentBuffer, contentSize); } //----------------------------------------------- return msgBuffer; } u8* PPMessage::BuildMessageEmpty() { return BuildMessage(nullptr, 0); } void PPMessage::BuildMessageHeader(u8 code) { g_code = code; } bool PPMessage::ParseHeader(u8* buffer) { if (IS_INVALID_CODE(buffer, 0)) { printf("Parse header failed. Validate code is incorrect: %c%c%c%c \n", buffer[0], buffer[1], buffer[2], buffer[3]); return false; } //----------------------------------------------------------- size_t readIndex = 4; g_code = READ_U8(buffer, readIndex); readIndex += 1; g_contentSize = READ_U32(buffer, readIndex); readIndex += 4; return true; } void PPMessage::ClearHeader() { g_code = 0; g_contentSize = 0; } ================================================ FILE: PinBox/PinBox/source/PPSession.cpp ================================================ #include "PPSession.h" #include "PPGraphics.h" #include "PPSessionManager.h" #include "ConfigManager.h" #define ONE_MILLISECOND 1000000ULL #define ONE_MICROSECOND 1000ULL #define BUFFERSIZE 0x1000 #define BUFFER_POOL_SIZE (BUFFERSIZE * 12) // static buffer to store socket data static u8* g_receivedBuffer; static u64 g_receivedSize; static u64 g_waitForSize; static u32 g_msgTag; namespace { // helpers void createNew(void* arg) { static_cast(arg)->threadMain(); } void createTest(void* arg) { static_cast(arg)->threadTest(); } } PPSession::PPSession() { // init static buffer g_receivedBuffer = (u8*)malloc(BUFFER_POOL_SIZE); g_receivedSize = 0; g_waitForSize = 0; g_msgTag = 0; } PPSession::~PPSession() { ReleaseSession(); CleanUp(); // free static buffer free(g_receivedBuffer); free(_ip); free(_port); } void PPSession::InitTestSession(PPSessionManager* manager, const char* ip, const char* port) { _testConnectionResult = 0; _manager = manager; _ip = strdup(ip); _port = strdup(port); s32 priority = 0; svcGetThreadPriority(&priority, CUR_THREAD_HANDLE); s32 t = priority - 2; if (t < 0x19) t = 0x19; // detached thread right after it created _thread = threadCreate(createTest, static_cast(this), 4 * 1024, t, -2, false); } void PPSession::InitSession(PPSessionManager* manager, const char* ip, const char* port) { _sendingMessages = std::queue(); _queueMessageMutex = new Mutex(); //------------------------------------------------------------- _manager = manager; _ip = strdup(ip); _port = strdup(port); //------------------------------------------------------------- _authenticated = false; s32 priority = 0; svcGetThreadPriority(&priority, CUR_THREAD_HANDLE); s32 t = priority - 2; if (t < 0x19) t = 0x19; _thread = threadCreate(createNew, static_cast(this), 4 * 1024, t, -2, false); } void PPSession::ReleaseSession() { if (!_running || _kill) return; _kill = true; _running = false; // join thread threadJoin(_thread, U64_MAX); threadFree(_thread); _thread = NULL; } void PPSession::CleanUp() { // clean up g_receivedSize = 0; g_waitForSize = 0; g_msgTag = 0; _authenticated = false; if (_tmpMessage) { delete _tmpMessage; } // cleanup hub for (HubItem* item : _hubItems) { if (item->thumbSize > 0) free(item->thumbBuf); delete item; } _hubItems.clear(); } void PPSession::StartStream() { _manager->InitDecoder(); // send message } void PPSession::StopStream() { _manager->ReleaseDecoder(); //TODO: we should clean all stream relate message left behide // send message } void PPSession::connectToServer() { _connect_state = CONNECTING; //_manager->SetSessionState(SS_CONNECTING); //-------------------------------------------------- // define socket _sock = socket(AF_INET, SOCK_STREAM, 0); if (_sock < 0) { printf("Can't create new socket.\n"); gfxFlushBuffers(); // Error: can't create socket _connect_state = FAIL; _manager->SetSessionState(SS_FAILED); return; } struct sockaddr_in addr = { 0 }; addr.sin_family = AF_INET; unsigned short nPort = (unsigned short)strtoul(_port, NULL, 0); addr.sin_port = htons(nPort); if(inet_pton(addr.sin_family, _ip, &addr.sin_addr) < 0) { printf("IP and Port not supported.\n", _ip, _port); gfxFlushBuffers(); _connect_state = FAIL; _manager->SetSessionState(SS_FAILED); return; } printf("Connect to: %s p:%s.\n", _ip, _port); gfxFlushBuffers(); int ret = connect(_sock, (struct sockaddr *) &addr, sizeof(addr)); if (ret < 0) { printf("Could not connect to server.\n"); gfxFlushBuffers(); _connect_state = FAIL; _manager->SetSessionState(SS_FAILED); return; } _connect_state = CONNECTED; _manager->SetSessionState(SS_CONNECTED); // set socket to non blocking so we can easy control it //fcntl(sockManager->sock, F_SETFL, O_NONBLOCK); fcntl(_sock, F_SETFL, fcntl(_sock, F_GETFL, 0) | O_NONBLOCK); printf("Connected to server.\n"); gfxFlushBuffers(); } void PPSession::closeConnect() { // set kill again to make sure it set // close connection if(_connect_state == CONNECTED) { Result rc = closesocket(_sock); if(rc != 0) { printf("Failed when close socket.\n"); } } _sock = -1; _connect_state = IDLE; printf("closed session.\n"); } void PPSession::recvSocketData() { //--------------------------------------------------------------------------------- // receive data //--------------------------------------------------------------------------------- int recvAmount = recv(_sock, g_receivedBuffer + g_receivedSize, BUFFERSIZE, 0); //TODO: Citra seem like can't use this method and it crash immedately if (recvAmount <= 0) { if (errno != EWOULDBLOCK) { printf("Error receive packet: %d\n", recvAmount); _kill = true; } return; }else if(recvAmount > BUFFERSIZE) { // sound like something are wrong here so we do notthing return; }else { g_receivedSize += recvAmount; } //printf("receive packet s:%d - total: %d - w:%d\n", recvAmount, g_receivedSize, g_waitForSize); //--------------------------------------------------------------------------------- // process data //--------------------------------------------------------------------------------- if (g_receivedSize < g_waitForSize || g_waitForSize == 0) return; int dataAfterProcess = g_receivedSize - g_waitForSize; do { // calculate data left u32 lastWaitForSize = g_waitForSize; // process message data processReceivedMsg(g_receivedBuffer, lastWaitForSize, g_msgTag); // shifting mem memcpy(g_receivedBuffer, g_receivedBuffer + lastWaitForSize, dataAfterProcess); // reset information g_receivedSize = dataAfterProcess; if(g_receivedSize < g_waitForSize || g_waitForSize == 0) return; dataAfterProcess = g_receivedSize - g_waitForSize; } while (dataAfterProcess >= 0); } void PPSession::sendMessageData() { _queueMessageMutex->Lock(); while(!_sendingMessages.empty()) { // get top message QueueMessage* queueMsg = (QueueMessage*)_sendingMessages.front(); _sendingMessages.pop(); if(queueMsg->msgSize > 0 && queueMsg->msgBuffer != nullptr) { u32 totalSent = 0; // send message do { int sendAmount = send(_sock, queueMsg->msgBuffer, queueMsg->msgSize, 0); if (sendAmount < 0) { // SS_FAILED when send message printf("Error when send message.\n"); ReleaseSession(); return; } totalSent += sendAmount; } while (totalSent < queueMsg->msgSize); //-------------------------------------------------------- // free message free(queueMsg->msgBuffer); delete queueMsg; } } _queueMessageMutex->Unlock(); } void PPSession::threadMain() { if (_running) return; _running = true; u64 sleepDuration = ONE_MILLISECOND * 2; // thread loop while (!_kill) { if (_connect_state == IDLE) { connectToServer(); } if (_connect_state == CONNECTED) { // check and recv data from server recvSocketData(); // send queue message sendMessageData(); } svcSleepThread(sleepDuration); } // send all message left sendMessageData(); std::queue().swap(_sendingMessages); delete _queueMessageMutex; // close connection closeConnect(); } void PPSession::threadTest() { if (_running) return; _running = true; u64 sleepDuration = ONE_MILLISECOND * 2; _testConnectionResult = 0; // thread loop while (!_kill) { if (_connect_state == IDLE) { connectToServer(); } if (_connect_state == CONNECTED) { _testConnectionResult = 1; } if (_connect_state == FAIL) { _testConnectionResult = -1; } svcSleepThread(sleepDuration); } // close connection closeConnect(); } void PPSession::RequestForData(u32 size, u32 tag) { g_waitForSize = size; g_msgTag = tag; } void PPSession::AddMessageToQueue(u8* msgBuffer, int32_t msgSize) { if (_running && _connect_state == CONNECTED && !_kill) { _queueMessageMutex->Lock(); QueueMessage *msg = new QueueMessage(); msg->msgBuffer = msgBuffer; msg->msgSize = msgSize; _sendingMessages.push(msg); _queueMessageMutex->Unlock(); } } void PPSession::processReceivedMsg(u8* buffer, u32 size, u32 tag) { //printf("process receive part size: %d - tag: %d.\n", size, tag); //------------------------------------------------------ // verify authentication //------------------------------------------------------ if (!_authenticated) { if (tag == PPREQUEST_AUTHEN) { PPMessage *authenMsg = new PPMessage(); if (authenMsg->ParseHeader(buffer)) if (authenMsg->GetMessageCode() == MSG_CODE_RESULT_AUTHENTICATION_SUCCESS) { printf("Authenticated successfully.\n"); _authenticated = true; _manager->SetBusyState(BS_NONE); // send message to get hub items and other information SendMsgRequestHubItems(); return; } else printf("Authenticaiton failed.\n"); else printf("Authenticaiton failed.\n"); delete authenMsg; } else printf("Client was not authentication.\n"); RequestForData(MSG_COMMAND_SIZE, PPREQUEST_AUTHEN); return; } //------------------------------------------------------ // process data by tag if (!_tmpMessage) _tmpMessage = new PPMessage(); switch (tag) { case PPREQUEST_HEADER: { if (_tmpMessage->ParseHeader(buffer)) { RequestForData(_tmpMessage->GetContentSize(), PPREQUEST_BODY); } else { _tmpMessage->ClearHeader(); RequestForData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); } break; } case PPREQUEST_BODY: { //// if tmp message is null that mean this is useless data then we avoid it //if (_tmpMessage->GetContentSize() == 0) { // _tmpMessage->ClearHeader(); // // we should prepare request for new header // RequestForData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); // return; //} // verify buffer size with message estimate size if (size == _tmpMessage->GetContentSize()) { processMessageData(buffer, size); // Request for next message RequestForData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); } //------------------------------------------------------ // remove message after use _tmpMessage->ClearHeader(); break; } default: break; } } void PPSession::processMessageData(u8* buffer, size_t size) { // process message data by message type switch (_tmpMessage->GetMessageCode()) { case MSG_CODE_REQUEST_NEW_SCREEN_FRAME: _manager->ProcessVideoFrame(buffer, size); break; case MSG_CODE_REQUEST_NEW_AUDIO_FRAME: //TODO: currently audio sleep make it all slow // should be avoid this by doing that in main thread _manager->ProcessAudioFrame(buffer, size); break; case MSG_CODE_RECEIVED_HUB_ITEMS: printf("Got hub items data\n"); // On get hub items list u32 cursor = 0; int i = 0; // read number of hub items u16 count = READ_U16(buffer, cursor); cursor += 2; u16 size; printf("Count: %d\n", count); // read hub items for(i = 0; i < count; ++i) { printf("> Read item: %d\n", i); HubItem *item = new HubItem(); // read type : 1 bytes u8 type = READ_U8(buffer, cursor); cursor += 1; item->type = type; printf("> Type: %d\n", type); // read uuid // size : 2 bytes size = READ_U16(buffer, cursor); cursor += 2; item->uuid.resize(size); memcpy(&item->uuid[0], buffer + cursor, size); cursor += size; printf("> uuid: %s :%d\n", item->uuid.c_str(), size); // read name // size : 2 bytes size = READ_U16(buffer, cursor); cursor += 2; item->name.resize(size); memcpy(&item->name[0], buffer + cursor, size); cursor += size; printf("> name: %s : %d\n", item->name.c_str(), size); if (type != HUB_SCREEN) { // read thumbnail // size : 4 bytes item->thumbSize = READ_U32(buffer, cursor); cursor += 4; #ifndef USE_CITRA // only work on N3ds device PPGraphics::Get()->AddCacheImage(&buffer[cursor], item->thumbSize, item->uuid); #else // Work around because of add direct buffer to cache make image unexpected behaviour std::string fname = "pinbox/tmp/" + item->uuid + ".png"; if (PPGraphics::Get()->AddCacheImage(fname.c_str(), item->uuid) == nullptr) { printf("Write cache file: %s\n", fname.c_str()); // save to file FILE *f = fopen(fname.c_str(), "wb"); if (f != NULL) { fwrite(buffer + cursor, sizeof(u8), item->thumbSize, f); fclose(f); PPGraphics::Get()->AddCacheImage(fname.c_str(), item->uuid); } } #endif cursor += item->thumbSize; } _hubItems.push_back(item); } _manager->SetBusyState(BS_NONE); _manager->SetSessionState(SS_PAIRED); break; default: break; } } //----------------------------------------------------- // screen capture //----------------------------------------------------- void PPSession::SendMsgAuthentication() { PPMessage *msg = new PPMessage(); msg->BuildMessageHeader(MSG_CODE_REQUEST_AUTHENTICATION_SESSION); u8* msgBuffer = msg->BuildMessageEmpty(); AddMessageToQueue(msgBuffer, msg->GetMessageSize()); RequestForData(MSG_COMMAND_SIZE, PPREQUEST_AUTHEN); delete msg; } void PPSession::SendMsgStartStream() { if (isSessionStarted) return; PPMessage *msg = new PPMessage(); msg->BuildMessageHeader(MSG_CODE_REQUEST_START_SCREEN_CAPTURE); u8* msgBuffer = msg->BuildMessageEmpty(); AddMessageToQueue(msgBuffer, msg->GetMessageSize()); isSessionStarted = true; delete msg; } void PPSession::SendMsgStopStream() { if (!isSessionStarted) return; //-------------------------------------- PPMessage *msg = new PPMessage(); msg->BuildMessageHeader(MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE); u8* msgBuffer = msg->BuildMessageEmpty(); AddMessageToQueue(msgBuffer, msg->GetMessageSize()); isSessionStarted = false; delete msg; //-------------------------------------- ReleaseSession(); } void PPSession::SendMsgChangeSetting() { PPMessage *authenMsg = new PPMessage(); authenMsg->BuildMessageHeader(MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE); //----------------------------------------------- // alloc msg content block size_t contentSize = 13; u8* contentBuffer = (u8*)malloc(sizeof(u8) * contentSize); u8* pointer = contentBuffer; //---------------------------------------------- // setting: wait for received frame //u8 _setting_waitToReceivedFrame = ConfigManager::Get()->_cfg_wait_for_received ? 1 : 0; //WRITE_U8(pointer, _setting_waitToReceivedFrame); //// setting: smooth frame number ( only activate if waitForReceivedFrame = true) //WRITE_U32(pointer, ConfigManager::Get()->_cfg_skip_frame); //// setting: frame quality [0 ... 100] //WRITE_U32(pointer, ConfigManager::Get()->_cfg_video_quality); //// setting: frame scale [0 ... 100] //WRITE_U32(pointer, ConfigManager::Get()->_cfg_video_scale); //----------------------------------------------- // build message u8* msgBuffer = authenMsg->BuildMessage(contentBuffer, contentSize); AddMessageToQueue(msgBuffer, authenMsg->GetMessageSize()); free(contentBuffer); delete authenMsg; } void PPSession::SendMsgRequestHubItems() { if (_connect_state == CONNECTED && _authenticated && _manager->GetBusyState() == BS_NONE) { printf("Request for hub items\n"); _manager->SetBusyState(BS_HUB_ITEMS); // cleanup items _hubItems.clear(); // send request PPMessage *msg = new PPMessage(); msg->BuildMessageHeader(MSG_CODE_REQUEST_HUB_ITEMS); u8* msgBuffer = msg->BuildMessageEmpty(); AddMessageToQueue(msgBuffer, msg->GetMessageSize()); RequestForData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); delete msg; } } //----------------------------------------------------- // Input //----------------------------------------------------- bool PPSession::SendMsgSendInputData(u32 down, u32 up, short cx, short cy, short ctx, short cty) { if (!isSessionStarted) return; PPMessage *msg = new PPMessage(); msg->BuildMessageHeader(MSG_CODE_SEND_INPUT_CAPTURE); //----------------------------------------------- // alloc msg content block const size_t contentSize = 16; u8* contentBuffer = (u8*)malloc(sizeof(u8) * contentSize); u8* pointer = contentBuffer; //---------------------------------------------- memcpy(pointer, &down, 4); memcpy(pointer + 4, &up, 4); memcpy(pointer + 8, &cx, 2); memcpy(pointer + 10, &cy, 2); memcpy(pointer + 12, &ctx, 2); memcpy(pointer + 14, &cty, 2); //----------------------------------------------- // build message and send u8* msgBuffer = msg->BuildMessage(contentBuffer, contentSize); AddMessageToQueue(msgBuffer, msg->GetMessageSize()); delete msg; return true; } ================================================ FILE: PinBox/PinBox/source/PPSessionManager.cpp ================================================ #include "PPSessionManager.h" #include "PPGraphics.h" #include "ConfigManager.h" #include "Logger.h" PPSessionManager::PPSessionManager() { } PPSessionManager::~PPSessionManager() { } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // connection test /////////////////////////////////////////////////////////////////////////////////////////////////////////// int PPSessionManager::TestConnection(ServerConfig* config) { if (_testSession != nullptr) { int ret = _testSession->GetTestConnectionResult(); printf("RET: %d.\n", ret); if(ret != 0) { delete _testSession; _testSession = NULL; _sessionState = SS_NOT_CONNECTED; } return ret; } printf("Init TEST connection to server.\n"); _testSession = new PPSession(); _testSession->InitTestSession(this, config->ip.c_str(), config->port.c_str()); return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // For current displaying video frame SessionState PPSessionManager::ConnectToServer(ServerConfig* config) { if (_session == nullptr) { printf("Init connection to server.\n"); _sessionState = SS_CONNECTING; _session = new PPSession(); _session->InitSession(this, config->ip.c_str(), config->port.c_str()); } return _sessionState; } void PPSessionManager::DisconnectToServer() { if (_sessionState == SS_NOT_CONNECTED) return; if (_session == nullptr) return; printf("Cleanup session.\n"); delete _session; _session = NULL; _sessionState = SS_NOT_CONNECTED; } void PPSessionManager::StartStreaming() { if (_sessionState != SS_PAIRED) return; //TODO: implement this } void PPSessionManager::StopStreaming() { if (_sessionState != SS_PAIRED) return; //TODO: implement this } void PPSessionManager::ProcessVideoFrame(u8* buffer, u32 size) { u8* rgbBuffer = _decoder->appendVideoBuffer(buffer, size); if (rgbBuffer != nullptr) PPGraphics::Get()->UpdateTopScreenSprite(rgbBuffer, 393216); //--------------------------------------------------------- // update frame video FPS //--------------------------------------------------------- if (!_receivedFirstVideoFrame) { _receivedFirstVideoFrame = true; _lastVideoTime = osGetTime(); _currentVideoFPS = 0.0f; _videoFrame = 0; } else { _videoFrame++; u64 deltaTime = osGetTime() - _lastVideoTime; if (deltaTime > 1000) { _currentVideoFPS = _videoFrame / (deltaTime / 1000.0f); _videoFrame = 0; _lastVideoTime = osGetTime(); } } } void PPSessionManager::DrawVideoFrame() { PPGraphics::Get()->DrawTopScreenSprite(); } void PPSessionManager::ProcessAudioFrame(u8* buffer, u32 size) { _decoder->decodeAudioStream(buffer, size); } void PPSessionManager::UpdateStreamSetting() { //_session->SendMsgChangeSetting(); } void PPSessionManager::GetControllerProfiles() { } void PPSessionManager::Authentication() { if (_sessionState != SS_CONNECTED || GetBusyState() != BS_NONE) return; SetBusyState(BS_AUTHENTICATION); _session->SendMsgAuthentication(); } void PPSessionManager::InitDecoder() { _decoder = new PPDecoder(); _decoder->initDecoder(); } void PPSessionManager::ReleaseDecoder() { _decoder->releaseDecoder(); } void PPSessionManager::UpdateInputStream(u32 down, u32 up, short cx, short cy, short ctx, short cty) { if (_session == nullptr) return; if(down != _oldDown || up != _oldUp || cx != _oldCX || cy != _oldCY || ctx != _oldCTX || cty != _oldCTY || !_initInputFirstFrame) { if(_session->SendMsgSendInputData(down, up, cx, cy, ctx, cty)) { _initInputFirstFrame = true; _oldDown = down; _oldUp = up; _oldCX = cx; _oldCY = cy; _oldCTX = ctx; _oldCTY = cty; } } } void PPSessionManager::StartFPSCounter() { _lastRenderTime = osGetTime(); _currentRenderFPS = 0.0f; _renderFrames = 0; } void PPSessionManager::UpdateFPSCounter() { _renderFrames++; u64 deltaTime = osGetTime() - _lastRenderTime; if(deltaTime > 1000) { _currentRenderFPS = _renderFrames / (deltaTime / 1000.0f); _renderFrames = 0; _lastRenderTime = osGetTime(); } } ================================================ FILE: PinBox/PinBox/source/PPUI.cpp ================================================ #include "PPUI.h" #include #include "ConfigManager.h" #include "Anim.h" volatile u32 kDown; volatile u32 kHeld; volatile u32 kUp; volatile u32 last_kDown; volatile u32 last_kHeld; volatile u32 last_kUp; static circlePosition cPos; static circlePosition cStick; static touchPosition kTouch; static touchPosition last_kTouch; static touchPosition first_kTouchDown; static touchPosition last_kTouchDown; volatile u64 holdTime = 0; static u32 sleepModeState = 0; //---------------------------------------- // Dialog //--------------------------------------- static bool mTmpLockTouch = false; static PopupCallback *mDialogBox; static PopupCallback *mDialogBoxCallLater; static DialogBoxOverride mDialogOverride; //---------------------------------------- // Tab //--------------------------------------- static int mPairedScreenTabIdx = 0; static int mHubItemSelectedIdx = -1; //---------------------------------------- // Scroll Box //--------------------------------------- static Vector2 mScrollLastTouch = Vector2{ -1,-1 }; static float mScrollSpeedModified = 0; static bool mScrolling = false; static u64 mTmpWaitTimer = 0; static std::vector mPopupList; static std::string mTemplateInputString = ""; static ServerConfig* mTmpServerConfig = nullptr; //---------------------------------------- // animations //---------------------------------------- static u64 mTmpLoadingTimeA = 0; static u64 mTmpLoadingTimeB = 0; static u64 mTmpLoadingTimeC = 0; static int mTmpLoadingDirA = 1; static int mTmpLoadingDirB = 1; static int mTmpLoadingDirC = 1; static const char* UI_INPUT_VALUE[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", ":" }; static const char* UI_KEYBOARD_VALUE[] = { "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", "a", "s", "d", "f", "g", "h", "j", "k", "l", "'", "z", "x", "c", "v", "b", "n", "m", ",", ".", " ", }; static const char* UI_TABS_PAIRED_SCREEN[] = { "Hub", "Basic Setting", "Advance Setting", }; u32 PPUI::getKeyDown() { return kDown; } u32 PPUI::getKeyHold() { return kHeld; } u32 PPUI::getKeyUp() { return kUp; } circlePosition PPUI::getLeftCircle() { return cPos; } circlePosition PPUI::getRightCircle() { return cStick; } u32 PPUI::getSleepModeState() { return sleepModeState; } void PPUI::UpdateInput() { //---------------------------------------- // store old input last_kDown = kDown; last_kHeld = kHeld; last_kUp = kUp; last_kTouch = kTouch; //---------------------------------------- // scan new input kDown = hidKeysDown(); kHeld = hidKeysHeld(); kUp = hidKeysUp(); cPos = circlePosition(); hidCircleRead(&cPos); cStick = circlePosition(); irrstCstickRead(&cStick); kTouch = touchPosition(); hidTouchRead(&kTouch); if(kDown & KEY_TOUCH) { first_kTouchDown = kTouch; last_kTouchDown = touchPosition(); } if(last_kHeld & KEY_TOUCH && kUp & KEY_TOUCH) { last_kTouchDown = kTouch; first_kTouchDown = touchPosition(); holdTime = 0; } } bool PPUI::TouchDownOnArea(float x, float y, float w, float h) { if (kDown & KEY_TOUCH || kHeld & KEY_TOUCH) { if (kTouch.px >= (u16)x && kTouch.px <= (u16)(x + w) && kTouch.py >= (u16)y && kTouch.py <= (u16)(y + h)) { return true; } } return false; } bool PPUI::TouchUpOnArea(float x, float y, float w, float h) { if ((last_kDown & KEY_TOUCH || last_kHeld & KEY_TOUCH) && kUp & KEY_TOUCH) { if (last_kTouch.px >= (u16)x && last_kTouch.px <= (u16)(x + w) && last_kTouch.py >= (u16)y && last_kTouch.py <= (u16)(y + h)) { return true; } } return false; } bool PPUI::TouchDown() { return kDown & KEY_TOUCH; } bool PPUI::TouchMove() { return kHeld & KEY_TOUCH; } bool PPUI::TouchUp() { return last_kHeld & KEY_TOUCH && kUp & KEY_TOUCH; } void PPUI::InitResource() { // create tmp folder struct stat st = { 0 }; if (stat("pinbox", &st) == -1) mkdir("pinbox", 0700); // create root pinbox folder if (stat("pinbox/tmp", &st) == -1) mkdir("pinbox/tmp", 0700); // create tmp folder for tmp asset cached // add static resources PPGraphics::Get()->AddCacheImageAsset("monitor.png", "monitor"); PPGraphics::Get()->AddCacheImageAsset("default_1.png", "default_1"); PPGraphics::Get()->AddCacheImageAsset("default_2.png", "default_2"); PPGraphics::Get()->AddCacheImageAsset("default_3.png", "default_3"); PPGraphics::Get()->AddCacheImageAsset("default_4.png", "default_4"); } void PPUI::CleanupResource() { } /////////////////////////////////////////////////////////////////////////// // TEXT /////////////////////////////////////////////////////////////////////////// int PPUI::DrawIdleTopScreen(PPSessionManager* sessionManager) { PPGraphics::Get()->DrawRectangle(0, 0, 400, 240, RGB(26, 188, 156)); LabelBox(0, 0, 400, 240, "PinBox", RGB(26, 188, 156), RGB(255, 255, 255)); } static Vector2 scrollboxTestCursor; int PPUI::DrawBtmServerSelectScreen(PPSessionManager* sm) { PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, RGB(236, 240, 241)); PPGraphics::Get()->DrawRectangle(0, 0, 320, 35, RGB(26, 188, 156)); // Screen title switch (sm->GetSessionState()) { case -1: LabelBox(55, 5, 200, 25, "Status: No Wifi Connection", RGB(26, 188, 156), RGB(255, 255, 255)); break; case 0: LabelBox(55, 5, 200, 25, "Status: Ready to Connect", RGB(26, 188, 156), RGB(255, 255, 255)); break; case 1: LabelBox(55, 5, 200, 25, "Status: Connecting...", RGB(26, 188, 156), RGB(255, 255, 255)); break; case 2: LabelBox(55, 5, 200, 25, "Status: Connected", RGB(26, 188, 156), RGB(255, 255, 255)); break; } // Quit if (FlatColorButton(5, 5, 50, 25, "Quit", RGB(214, 48, 49), RGB(255, 118, 117), RGB(255, 255, 255), 6.f)) { OverrideDialogTypeCritical(); DrawDialogMessage(sm, "Warning", "Are you sure to quit?", [=]() { // on cancel return -1; }, [=]() { // on ok return RET_CLOSE_APP; }); } // Add new Server if (FlatColorButton(260, 5, 50, 25, "Add", RGB(9, 132, 227), RGB(116, 185, 255), RGB(255, 255, 255), 6.f)) { AddPopup([=]() { if(mTmpServerConfig == nullptr) { mTmpServerConfig = new ServerConfig(); mTmpServerConfig->name = "My Local PC"; mTmpServerConfig->ip = "127.0.0.1"; mTmpServerConfig->port = "1234"; } return DrawBtmAddNewServerProfileScreen(sm, [=](void* a, void* b) { delete mTmpServerConfig; mTmpServerConfig = nullptr; // on cancel }, [=](void* a, void* b) { // add to list ConfigManager::Get()->servers.push_back(ServerConfig(*mTmpServerConfig)); ConfigManager::Get()->Save(); //TODO: error here when save delete mTmpServerConfig; mTmpServerConfig = nullptr; // on ok } ); }); } // List servers if(ConfigManager::Get()->servers.size() > 0) { //TODO: scroll box float boxHeight = 40; for(int i = 0; i < ConfigManager::Get()->servers.size(); ++i) { float sx = 40 + boxHeight * i + 5 * i; // Draw BG PPGraphics::Get()->DrawRectangle(0, sx, 320, boxHeight, RGB(223, 228, 234)); // Server name LabelBoxLeft(70, sx + 2, 150, 20, ConfigManager::Get()->servers[i].name.c_str(), TRANSPARENT, RGB(47, 53, 66), 0.7); LabelBoxLeft(70, sx + 25, 150, 10, (ConfigManager::Get()->servers[i].ip + ":" + ConfigManager::Get()->servers[i].port).c_str(), TRANSPARENT, RGB(116, 125, 140), 0.45); // Connect button if (FlatColorButton(5, sx + 2, 60, 32, "Connect", RGB(46, 213, 115), RGB(123, 237, 159), RGB(47, 53, 66), 6.f) && sm->GetSessionState() == SS_NOT_CONNECTED) { mTmpWaitTimer = osGetTime(); OverrideDialogTypeInfo(); DrawDialogLoading("Connecting", "Make sure start server on your PC\nPlease be patient while app working.", [=]() { SessionState state = sm->ConnectToServer(&ConfigManager::Get()->servers[i]); switch (state) { case SS_CONNECTED: if (osGetTime() - mTmpWaitTimer > (1 * TIME_SECOND)) { OverrideDialogTypeSuccess(); OverrideDialogContent("Authentication", "Please wait for handshaking\nand verify client."); //send authentication message if (osGetTime() - mTmpWaitTimer > (2 * TIME_SECOND)) { sm->Authentication(); } } return 0; case SS_PAIRED: // reset variable of paired screen mPairedScreenTabIdx = 0; return -1; case SS_FAILED: if (osGetTime() - mTmpWaitTimer > (1 * TIME_SECOND)) { mDialogBoxCallLater = new PopupCallback([=]() { // We need set session manager back to not connected state // because of other state can't go there so it must be SS_FAILED OverrideDialogTypeCritical(); DrawDialogMessage(sm, "Error", "Can't connect to server for some reason.", [=]() { sm->DisconnectToServer(); return -1; }); return 0; }); return -1; } return 0; default: return 0; } return 0; }); } // Remove button if (FlatColorButton(286, sx + 6, 26, 26, "X", RGB(255, 71, 87), RGB(255, 107, 129), RGB(255, 255, 255), 13.f)) { DrawDialogMessage(sm, "Warning", "Are you sure to remove this profile?", [=]() { // on cancel return -1; }, [=]() { // on ok ConfigManager::Get()->servers.erase(ConfigManager::Get()->servers.begin() + i); ConfigManager::Get()->Save(); return -1; }); } } }else { // Draw empty screen and tutorial LabelBoxAutoWrap(10, 45, 300, 185, "No server profile found.\nPlease add new one by Add button.", TRANSPARENT, PPGraphics::Get()->PrimaryTextColor); } // test scroll box scrollboxTestCursor = ScrollBox(10, 100, 300, 100, D_HORIZONTAL, scrollboxTestCursor, [=]() { PPGraphics::Get()->DrawRectangle(10, 100, 300, 100, RGB(240, 147, 43)); WH wh{ 1500, 300 }; return wh; }); // Dialog box ( alway at bottom so it will draw on top ) return DrawDialogBox(sm); } int PPUI::DrawBtmAddNewServerProfileScreen(PPSessionManager* sessionManager, ResultCallback cancel, ResultCallback ok) { PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, RGB(236, 240, 241)); PPGraphics::Get()->DrawRectangle(0, 0, 320, 25, RGB(26, 188, 156)); // Screen title LabelBox(0, 5, 320, 20, "Add New Server", RGB(26, 188, 156), RGB(255, 255, 255)); // Input server name LabelBoxLeft(5, 30, 100, 30, "Server Name", TRANSPARENT, RGB(44, 62, 80)); if (LabelBox(105, 30, 210, 30, mTmpServerConfig->name.c_str(), PPGraphics::Get()->PrimaryColor, RGB(255, 255, 255), 0.5f, 6.f)) { mTemplateInputString = std::string(mTmpServerConfig->name); DrawDialogKeyboard([=](void* a, void* b) {}, [=](void* a, void* b) { // ok mTmpServerConfig->name.clear(); mTmpServerConfig->name.append(mTemplateInputString); mTemplateInputString = ""; }); } // Input server ip LabelBoxLeft(5, 70, 100, 30, "Server IP", TRANSPARENT, RGB(44, 62, 80)); if (LabelBox(105, 70, 210, 30, mTmpServerConfig->ip.c_str(), PPGraphics::Get()->PrimaryColor, RGB(255, 255, 255), 0.5f, 6.f)) { mTemplateInputString = std::string(mTmpServerConfig->ip); DrawDialogNumberInput([=](void* a, void* b) {}, [=](void* a, void* b) { // ok mTmpServerConfig->ip.clear(); mTmpServerConfig->ip.append(mTemplateInputString); mTemplateInputString = ""; }); } // Input server port LabelBoxLeft(5, 110, 100, 30, "Server Port", TRANSPARENT, RGB(44, 62, 80)); if (LabelBox(105, 110, 210, 30, mTmpServerConfig->port.c_str(), PPGraphics::Get()->PrimaryColor, RGB(255, 255, 255), 0.5f, 6.f)) { mTemplateInputString = std::string(mTmpServerConfig->port); DrawDialogNumberInput([=](void* a, void* b) {}, [=](void* a, void* b) { // ok mTmpServerConfig->port.clear(); mTmpServerConfig->port.append(mTemplateInputString); mTemplateInputString = ""; }); } // Cancel button if (FlatColorButton(10, 200, 50, 30, "Cancel", RGB(192, 57, 43), RGB(231, 76, 60), RGB(223, 228, 234), 6.f)) { ClosePopup(); if (cancel != nullptr) cancel(nullptr, nullptr); } // OK button if (FlatColorButton(260, 200, 50, 30, "OK", RGB(41, 128, 185), RGB(52, 152, 219), RGB(223, 228, 234), 6.f)) { mTmpWaitTimer = osGetTime(); OverrideDialogTypeInfo(); DrawDialogLoading("Testing connection", "Make sure start server on your PC\nPlease be patient while app working", [=]() { if (osGetTime() - mTmpWaitTimer > (2 * TIME_SECOND)) { // return -1 for finish loading int ret = sessionManager->TestConnection(mTmpServerConfig); if (ret == 1) { mDialogBoxCallLater = new PopupCallback([=]() { OverrideDialogTypeSuccess(); DrawDialogMessage(sessionManager, "Good Work", "Connection to server seem good!"); ClosePopup(); if (ok != nullptr) ok(nullptr, nullptr); return 0; }); return -1; } else if (ret == -1) { mDialogBoxCallLater = new PopupCallback([=]() { OverrideDialogTypeCritical(); DrawDialogMessage(sessionManager, "Error", "Can't Connect to server!"); return 0; }); return -1; } } return 0; }); } // Dialog box ( alway at bottom so it will draw on top ) return DrawDialogBox(sessionManager); } int PPUI::DrawBtmPairedScreen(PPSessionManager* sm) { PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, RGB(236, 240, 241)); PPGraphics::Get()->DrawRectangle(0, 0, 320, 35, RGB(178, 190, 195)); //TODO: need loop check for wifi status // if wifi was turn off we need close connection and return to Select Server Screen // Disconnect to server if (FlatColorButton(5, 5, 80, 25, "Disconnect", RGB(214, 48, 49), RGB(255, 118, 117), RGB(255, 255, 255), 6.f)) { OverrideDialogTypeCritical(); DrawDialogMessage(sm, "Warning", "Are you sure to disconnect?", [=]() { // on cancel return -1; }, [=]() { // on ok sm->DisconnectToServer(); return -1; }); } // LOGO LabelBox(130, 0, 60, 35, "PinBox", TRANSPARENT, RGB(47, 53, 66), 0.9f); // Stream / Stop button // only display when selected an item and in hub tab if (mHubItemSelectedIdx >= 0 && mPairedScreenTabIdx == 0) { if (FlatColorButton(240, 5, 70, 25, "Stream", RGB(46, 213, 115), RGB(123, 237, 159), RGB(47, 53, 66), 6.f)) { } } // Case selection if (sm ->GetSessionState() == SS_PAIRED) { // Draw config tabs // Tab 1: Stream mode / Stream quality ( basic setting ) int ret = DrawTabs(UI_TABS_PAIRED_SCREEN, 3, mPairedScreenTabIdx, 0, 40, 320, 200); switch (ret) { case 0: mPairedScreenTabIdx = ret; break; case 1: mPairedScreenTabIdx = ret; break; case 2: OverrideDialogTypeCritical(); DrawDialogMessage(sm, "Warning", "Modified setting in here maybe cause\ncrash or unexpected behaviour\nMake sure you know what you doing.", [=]() { // on cancel return -1; }, [=]() { // on ok mPairedScreenTabIdx = ret; return -1; }); break; } switch (mPairedScreenTabIdx) { case 0: { //========================================================== // HUB ITEMS SCREEN //========================================================== int hubCount = sm->GetHubItemCount(); int posY = 0; int posX = 0; for (int i = 0; i < hubCount; ++i) { HubItem* hItem = sm->GetHubItem(i); // get sprite Sprite* hSprite = nullptr; if (hItem->type == HUB_SCREEN) { hSprite = PPGraphics::Get()->GetCacheImage("monitor"); } else { hSprite = PPGraphics::Get()->GetCacheImage(hItem->uuid.c_str()); } // display config int itemSpaceX = 48; int itemSpaceY = 32; int thumbSize = 48; int cx = 0, cy = 75; int ix = cx + 25 + posX; int iy = cy + 5 + (thumbSize + itemSpaceY) * posY; // draw background if(SelectBox(ix - 15, iy - 5, thumbSize + 30, thumbSize + 25, mHubItemSelectedIdx == i ? RGB(30, 144, 255) : RGB(241, 242, 246), 6.0f)) { if (mHubItemSelectedIdx != i) mHubItemSelectedIdx = i; else mHubItemSelectedIdx = -1; } // draw image PPGraphics::Get()->DrawImage(hSprite, ix, iy, thumbSize, thumbSize); LabelBox(ix, iy + thumbSize, thumbSize, 25, hItem->name.c_str(), TRANSPARENT, mHubItemSelectedIdx == i ? RGB(241, 242, 246) : RGB(47, 53, 66)); //--- move along posY++; if (posY >= 2) { posY = 0; posX += thumbSize + itemSpaceX; } } break; } case 1: { //========================================================== // BASIC CONFIG SCREEN //========================================================== HubItem* hItem = sm->GetHubItem(2); Sprite* hSprite = PPGraphics::Get()->GetCacheImage(hItem->uuid.c_str()); PPGraphics::Get()->DrawImage(hSprite, 100, 100, 48, 48); break; } case 2: { //========================================================== // ADVANCE CONFIG SCREEN //========================================================== HubItem* hItem = sm->GetHubItem(3); Sprite* hSprite = PPGraphics::Get()->GetCacheImage(hItem->uuid.c_str()); PPGraphics::Get()->DrawImage(hSprite, 100, 100, 48, 48); break; } } } else if(sm->GetSessionState() == SS_STREAMING) { } // Dialog box ( alway at bottom so it will draw on top ) return DrawDialogBox(sm); } void PPUI::OverrideDialogTypeWarning() { mDialogOverride.isActivate = true; mDialogOverride.TitleBgColor = RGB(255, 127, 80); mDialogOverride.TitleTextColor = RGB(47, 53, 66); } void PPUI::OverrideDialogTypeInfo() { mDialogOverride.isActivate = true; mDialogOverride.TitleBgColor = RGB(112, 161, 255); mDialogOverride.TitleTextColor = RGB(47, 53, 66); } void PPUI::OverrideDialogTypeSuccess() { mDialogOverride.isActivate = true; mDialogOverride.TitleBgColor = RGB(123, 237, 159); mDialogOverride.TitleTextColor = RGB(47, 53, 66); } void PPUI::OverrideDialogTypeCritical() { mDialogOverride.isActivate = true; mDialogOverride.TitleBgColor = RGB(255, 71, 87); mDialogOverride.TitleTextColor = RGB(47, 53, 66); } void PPUI::OverrideDialogContent(const char* title, const char* body) { mDialogOverride.isActivate = true; mDialogOverride.Title = title; mDialogOverride.Body = body; } int PPUI::DrawDialogKeyboard(ResultCallback cancelCallback, ResultCallback okCallback) { if (mDialogBox) return 0; mDialogBox = new PopupCallback([=]() { // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box float boxY = 30; float boxHeight = 180; PPGraphics::Get()->DrawRectangle(13, boxY - 2, 294, boxHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor); PPGraphics::Get()->DrawRectangle(15, boxY, 290, boxHeight, RGB(247, 247, 247)); // Input display LabelBox(22, boxY + 15, 276, 30, mTemplateInputString.c_str(), mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, RGB(247, 247, 247)); // Keyboard Number int kW = 28; float startX = 22, startY = 60 + boxY; for (int c = 0; c < 10; c++) { for (int r = 0; r < 3; r++) { if (FlatButton(startX + c * kW, startY + r * kW, kW - 4, kW - 4, UI_KEYBOARD_VALUE[c + r * 10])) { char v = *UI_KEYBOARD_VALUE[c + r * 10]; mTemplateInputString.push_back(v); } } } // Cancel button if (FlatColorButton(22, boxY + boxHeight - 30, 56, 25, "Cancel", PPGraphics::Get()->AccentColor, PPGraphics::Get()->AccentDarkColor, PPGraphics::Get()->AccentTextColor)) { mTemplateInputString = ""; cancelCallback(nullptr, nullptr); return -1; } // Delete Button if (FlatColorButton(192, boxY + boxHeight - 30, 56, 25, "Delete", PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryDarkColor, RGB(247, 247, 247))) { if (mTemplateInputString.size() > 0) { mTemplateInputString.erase(mTemplateInputString.end() - 1); } } // OK Button if (FlatColorButton(258, boxY + boxHeight - 30, 40, 25, "OK", PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryDarkColor, RGB(247, 247, 247))) { okCallback(nullptr, nullptr); return -1; } return 0; }); return 0; } int PPUI::DrawDialogNumberInput(ResultCallback cancelCallback, ResultCallback okCallback) { if (mDialogBox) return 0; mDialogBox = new PopupCallback([=]() { // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box float boxY = 30; float boxHeight = 180; PPGraphics::Get()->DrawRectangle(13, boxY - 2, 294, boxHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor); PPGraphics::Get()->DrawRectangle(15, boxY, 290, boxHeight, RGB(247, 247, 247)); // Input display LabelBox(22, boxY + 15, 276, 30, mTemplateInputString.c_str(), mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, RGB(247, 247, 247)); // Keyboard Number int kW = 28; float startX = 22, startY = 60 + boxY; for (int c = 0; c < 3; c++) { for (int r = 0; r < 4; r++) { if (FlatButton(startX + c * kW, startY + r * kW, kW - 4, kW - 4, UI_INPUT_VALUE[c + r * 3])) { char v = *UI_INPUT_VALUE[c + r * 3]; mTemplateInputString.push_back(v); } } } // Cancel button if (FlatColorButton(238, boxY + boxHeight - 30, 56, 25, "Cancel", PPGraphics::Get()->AccentColor, PPGraphics::Get()->AccentDarkColor, PPGraphics::Get()->AccentTextColor)) { mTemplateInputString = ""; cancelCallback(nullptr, nullptr); return -1; } // Delete Button if (FlatColorButton(192, startY, 56, 25, "Delete", PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryDarkColor, RGB(247, 247, 247))) { if (mTemplateInputString.size() > 0) { mTemplateInputString.erase(mTemplateInputString.end() - 1); } } // OK Button if (FlatColorButton(258, startY, 40, 25, "OK", PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryDarkColor, RGB(247, 247, 247))) { okCallback(nullptr, nullptr); return -1; } return 0; }); return 0; } int PPUI::DrawDialogLoading(const char* title, const char* body, PopupCallback callback) { if (mDialogBox) return 0; mTmpLoadingDirA = 1; mTmpLoadingDirB = 1; mTmpLoadingTimeA = osGetTime(); mTmpLoadingTimeB = osGetTime(); mDialogBox = new PopupCallback([=]() { Vector3 bodySize = PPGraphics::Get()->GetTextSizeAutoWrap(body, 0.5, 0.5, 280); float popupHeight = bodySize.y + 40 + 36; if (popupHeight > 220) popupHeight = 220; float spaceY = (240.0f - popupHeight) / 2.0f; // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box PPGraphics::Get()->DrawRectangle(13, spaceY, 294, popupHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, 6.0f); PPGraphics::Get()->DrawRectangle(15, spaceY + 2, 290, popupHeight, RGB(247, 247, 247), 6.0f); // draw title LabelBox(15, spaceY + 2, 290, 30, mDialogOverride.isActivate && mDialogOverride.Title != nullptr ? mDialogOverride.Title : title, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryTextColor, 0.8); LabelBoxAutoWrap(20, spaceY + 40, 280, bodySize.y, mDialogOverride.isActivate && mDialogOverride.Body ? mDialogOverride.Body : body, RGB(255, 255, 255), PPGraphics::Get()->PrimaryTextColor); // animation part float minX = 60, maxX = 250; float minW = 15, maxW = 55; double duration = 1.0 * 1000ULL; double durationW = duration / 2.0; u64 timePassA = osGetTime() - mTmpLoadingTimeA; u64 timePassB = osGetTime() - mTmpLoadingTimeB; double p = (double)timePassA / duration; if (mTmpLoadingDirA == -1) p = 1.0 - p; double e = getEasingFunction(EaseInOutExpo)(p); float currentX = minX + e * (maxX - minX); double pW = (double)timePassB / durationW; if (mTmpLoadingDirB == -1) pW = 1.0 - pW; double eW = getEasingFunction(EaseInQuint)(pW); float currentW = minW + eW * (maxW - minW); PPGraphics::Get()->DrawRectangle(currentX, spaceY + 40 + bodySize.y + 4, currentW, 15, RGB(255, 165, 2), 7.5f); if (timePassA >= duration) { mTmpLoadingTimeA = osGetTime(); mTmpLoadingDirA *= -1; } if (timePassB >= durationW) { mTmpLoadingTimeB = osGetTime(); mTmpLoadingDirB *= -1; } return callback(); }); return 0; } int PPUI::DrawDialogMessage(PPSessionManager* sessionManager, const char* title, const char* body) { if (mDialogBox) return 0; mDialogBox = new PopupCallback([=]() { Vector3 bodySize = PPGraphics::Get()->GetTextSizeAutoWrap(body, 0.5, 0.5, 280); float popupHeight = bodySize.y + 40 + 36; if (popupHeight > 220) popupHeight = 220; float spaceY = (240.0f - popupHeight) / 2.0f; // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box PPGraphics::Get()->DrawRectangle(13, spaceY, 294, popupHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, 6.0f); PPGraphics::Get()->DrawRectangle(15, spaceY + 2, 290, popupHeight, RGB(247, 247, 247), 6.0f); // draw title LabelBox(15, spaceY + 2, 290, 30, title, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryTextColor, 0.8); LabelBoxAutoWrap(20, spaceY + 40, 280, bodySize.y, body, RGB(255, 255, 255), PPGraphics::Get()->PrimaryTextColor); // draw button close if(FlatColorButton(135, spaceY + 40 + bodySize.y + 4, 50, 30, "Close", PPGraphics::Get()->AccentColor, PPGraphics::Get()->AccentDarkColor, PPGraphics::Get()->AccentTextColor, 6.0f)) { return -1; } return 0; }); return 0; } int PPUI::DrawDialogMessage(PPSessionManager* sessionManager, const char* title, const char* body, PopupCallback closeCallback) { if (mDialogBox) return 0; mDialogBox = new PopupCallback([=]() { Vector3 bodySize = PPGraphics::Get()->GetTextSizeAutoWrap(body, 0.5, 0.5, 280); float popupHeight = bodySize.y + 40 + 36; if (popupHeight > 220) popupHeight = 220; float spaceY = (240.0f - popupHeight) / 2.0f; // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box PPGraphics::Get()->DrawRectangle(13, spaceY, 294, popupHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, 6.0f); PPGraphics::Get()->DrawRectangle(15, spaceY + 2, 290, popupHeight, RGB(247, 247, 247), 6.0f); // draw title LabelBox(15, spaceY + 2, 290, 30, title, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryTextColor, 0.8); LabelBoxAutoWrap(20, spaceY + 40, 280, bodySize.y, body, RGB(255, 255, 255), PPGraphics::Get()->PrimaryTextColor); // draw button close if (FlatColorButton(135, spaceY + 40 + bodySize.y + 4, 50, 30, "Close", PPGraphics::Get()->AccentColor, PPGraphics::Get()->AccentDarkColor, PPGraphics::Get()->AccentTextColor, 6.0f)) { return closeCallback(); } return 0; }); return 0; } int PPUI::DrawDialogMessage(PPSessionManager* sessionManager, const char* title, const char* body, PopupCallback cancelCallback, PopupCallback okCallback) { if (mDialogBox) return 0; mDialogBox = new PopupCallback([=]() { Vector3 bodySize = PPGraphics::Get()->GetTextSizeAutoWrap(body, 0.5, 0.5, 280); float popupHeight = bodySize.y + 40 + 36; if (popupHeight > 220) popupHeight = 220; float spaceY = (240.0f - popupHeight) / 2.0f; // draw background PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, PPGraphics::Get()->TransBackgroundDark); // draw dialog box PPGraphics::Get()->DrawRectangle(13, spaceY, 294, popupHeight + 4, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, 6.0f); PPGraphics::Get()->DrawRectangle(15, spaceY + 2, 290, popupHeight, RGB(247, 247, 247), 6.0f); // draw title LabelBox(15, spaceY + 2, 290, 30, title, mDialogOverride.isActivate ? mDialogOverride.TitleBgColor : PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryTextColor, 0.8); LabelBoxAutoWrap(20, spaceY + 40, 280, bodySize.y, body, RGB(255, 255, 255), PPGraphics::Get()->PrimaryTextColor); // draw button close if (FlatColorButton(115, spaceY + 40 + bodySize.y + 4, 40, 30, "Close", PPGraphics::Get()->AccentColor, PPGraphics::Get()->AccentDarkColor, PPGraphics::Get()->AccentTextColor, 6.0f)) { return cancelCallback(); } // draw button ok if (FlatColorButton(165, spaceY + 40 + bodySize.y + 4, 40, 30, "OK", PPGraphics::Get()->PrimaryColor, PPGraphics::Get()->PrimaryDarkColor, PPGraphics::Get()->PrimaryTextColor, 6.0f)) { return okCallback(); } return 0; }); return 0; } int PPUI::DrawStreamConfigUI(PPSessionManager* sessionManager, ResultCallback cancel, ResultCallback ok) { PPGraphics::Get()->DrawRectangle(0, 0, 320, 240, RGB(236, 240, 241)); LabelBox(0, 0, 320, 30, "Advance Config", RGB(26, 188, 156), RGB(255, 255, 255)); //ConfigManager::Get()->_cfg_video_quality = Slide(5, 40, 300, 30, ConfigManager::Get()->_cfg_video_quality, 10, 100, "Quality"); //ConfigManager::Get()->_cfg_video_scale = Slide(5, 70, 300, 30, ConfigManager::Get()->_cfg_video_scale, 10, 100, "Scale"); //ConfigManager::Get()->_cfg_skip_frame = Slide(5, 100, 300, 30, ConfigManager::Get()->_cfg_skip_frame, 0, 60, "Skip Frame"); //ConfigManager::Get()->_cfg_wait_for_received = ToggleBox(5, 130, 300, 30, ConfigManager::Get()->_cfg_wait_for_received, "Wait Received"); // Cancel button if (FlatColorButton(200, 200, 50, 30, "Cancel", RGB(192, 57, 43), RGB(231, 76, 60), RGB(255, 255, 255))) { ClosePopup(); cancel(nullptr, nullptr); } // OK button if (FlatColorButton(260, 200, 50, 30, "OK", RGB(41, 128, 185), RGB(52, 152, 219), RGB(255, 255, 255))) { ClosePopup(); ok(nullptr, nullptr); } } int PPUI::DrawIdleBottomScreen(PPSessionManager* sessionManager) { // touch screen to wake up if(TouchUpOnArea(0,0, 320, 240)) { sleepModeState = 1; } // label LabelBox(0, 0, 320, 240, "Touch screen to wake up", RGB(0, 0, 0), RGB(125, 125, 125)); InfoBox(sessionManager); return 0; } void PPUI::InfoBox(PPSessionManager* sessionManager) { // render video FPS char videoFpsBuffer[100]; snprintf(videoFpsBuffer, sizeof videoFpsBuffer, "FPS:%.1f|VPS:%.1f", sessionManager->GetFPS(), sessionManager->GetVideoFPS()); LabelBoxLeft(5, 220, 100, 20, videoFpsBuffer, TRANSPARENT, RGB(150, 150, 150), 0.4f); snprintf(videoFpsBuffer, sizeof videoFpsBuffer, "CPU:%.1f|GPU:%.1f|CMD:%.1f", C3D_GetProcessingTime()*6.0f, C3D_GetDrawingTime()*6.0f, C3D_GetCmdBufUsage()*100.0f); LabelBoxLeft(5, 210, 100, 20, videoFpsBuffer, TRANSPARENT, RGB(150, 150, 150), 0.4f); } int PPUI::DrawTabs(const char* tabs[], u32 tabCount, int activeTab, float x, float y, float w, float h) { int ret = -1; float tabPadding = 10; float cX = x + tabPadding / 2; Color separetorActive = RGB(85, 239, 196); separetorActive.lighten(0.2f); Color separetor = RGB(178, 190, 195); separetor.lighten(0.2f); // Draw tab part for(int i = 0; i < tabCount; ++i) { const Vector2 tabTitleSize = PPGraphics::Get()->GetTextSize(tabs[i], 0.5f, 0.5f); // tab button if (FlatColorButton(cX, y + (activeTab == i ? 0 : tabPadding/2), tabTitleSize.x + tabPadding * 2, 25 + (activeTab == i ? tabPadding / 2 : 0), tabs[i], activeTab == i ? RGB(30, 144, 255) : RGB(223, 228, 234), activeTab == i ? RGB(83, 82, 237) : RGB(30, 144, 255), activeTab == i ? RGB(241, 242, 246) : RGB(47, 53, 66))) { ret = i; } cX += tabTitleSize.x + tabPadding * 2; // separetor line PPGraphics::Get()->DrawRectangle(cX - 1, y + (activeTab == i ? 0 : tabPadding / 2), 1, 25 + (activeTab == i ? tabPadding / 2 : 0), activeTab == i ? separetorActive : separetor); } // Draw content background and scroll if need float cY = y + tabPadding / 2 + 25; PPGraphics::Get()->DrawRectangle(x, cY, w, h - (tabPadding / 2 + 25), RGB(223, 228, 234)); return ret; } int PPUI::DrawDialogBox(PPSessionManager* sessionManager) { if (mDialogBox != nullptr) { mTmpLockTouch = false; int ret = (*mDialogBox)(); mTmpLockTouch = true; if(ret < 0) { mTmpLockTouch = false; delete mDialogBox; mDialogBox = nullptr; // disable override after finish dialog mDialogOverride.isActivate = false; mDialogOverride.Title = nullptr; mDialogOverride.Body = nullptr; // trigger call later after finish dialog if(mDialogBoxCallLater != nullptr) { (*mDialogBoxCallLater)(); delete mDialogBoxCallLater; mDialogBoxCallLater = nullptr; } if (ret == RET_CLOSE_APP) return -1; } } return 0; } Vector2 PPUI::ScrollBox(float x, float y, float w, float h, Direction dir, Vector2 cursor, WHCallback contentDraw) { PPGraphics::Get()->StartMasked(x, y, w, h, GFX_BOTTOM); // return content size after drawing WH ret = contentDraw(); // check for touch scrolling Vector2 dif; if (TouchDownOnArea(x, y, w, h) && !mTmpLockTouch) { dif = Vector2{ (float)kTouch.px - mScrollLastTouch.x, (float)kTouch.py - mScrollLastTouch.y }; if (mScrolling) { // calculate speed modifier if (abs(dif.x) >= 3 && (dir == D_HORIZONTAL || dir == D_BOTH)) { mScrollSpeedModified += SCROLL_SPEED_STEP; } if (abs(dif.y) >= 3 && (dir == D_VERTICAL || dir == D_BOTH)) { mScrollSpeedModified += SCROLL_SPEED_STEP; } } // check if not scrolling yet if(!mScrolling && mScrollLastTouch.x > -1.f) { if(abs(dif.x) >= SCROLL_THRESHOLD && (dir == D_HORIZONTAL || dir == D_BOTH)) { mScrolling = true; } if (abs(dif.y) >= SCROLL_THRESHOLD && (dir == D_VERTICAL || dir == D_BOTH)) { mScrolling = true; } } mScrollLastTouch = Vector2{ (float)kTouch.px ,(float)kTouch.py }; }else { mScrollLastTouch = Vector2{ -1.0f, -1.0f }; mScrolling = false; mScrollSpeedModified = SCROLL_SPEED_MODIFIED; } // check for scroll box switch (dir) { case D_NONE: { // Do not display scroll bar break; } case D_HORIZONTAL: { Vector2 maxScroll = { ret.width - w , 0 }; float p2c = w / (float)ret.width; if (p2c < SCROLL_BAR_MIN) p2c = SCROLL_BAR_MIN; // only display scroll bar if percent is small than 1.0 if (p2c < 1.0f) { float bW = floorf(p2c * w); if (mScrolling) { cursor.x += (float)dif.x + mScrollSpeedModified * (float)dif.x; if (cursor.x > maxScroll.x) cursor.x = maxScroll.x; if (cursor.x < 0) cursor.x = 0; //TODO: cursor are use for content drawing display } float moveableW = w - bW - 8; // 8 is padding float barMovePercent = cursor.x / maxScroll.x; PPGraphics::Get()->DrawRectangle(x + 4 + floorf(moveableW * barMovePercent), y + h - 10, bW, 6, RGBA(83, 92, 104, 150), 3.0f); } break; } case D_VERTICAL: { Vector2 maxScroll = { 0 , ret.height - h }; float p2c = h / (float)ret.height; if (p2c < SCROLL_BAR_MIN) p2c = SCROLL_BAR_MIN; // only display scroll bar if percent is small than 1.0 if (p2c < 1.0f) { float bH = floorf(p2c * h); if (mScrolling) { cursor.y = y + (float)dif.y +mScrollSpeedModified * (float)dif.y; if (cursor.y > maxScroll.y) cursor.y = maxScroll.y; if (cursor.y < 0) cursor.y = 0; } float moveableH = h - bH - 8; // 8 is padding float barMovePercent = cursor.y / maxScroll.y; PPGraphics::Get()->DrawRectangle(x + w - 10, y + 4 + floorf(moveableH * barMovePercent), 6, bH, RGBA(83, 92, 104, 150), 3.0f); } break; } case D_BOTH: { break; } default: { }; } PPGraphics::Get()->StopMasked(); return cursor; } /////////////////////////////////////////////////////////////////////////// // SLIDE /////////////////////////////////////////////////////////////////////////// float PPUI::Slide(float x, float y, float w, float h, float val, float min, float max, float step, const char* label) { Vector2 tSize = PPGraphics::Get()->GetTextSize(label, 0.5f, 0.5f); float labelY = (h - tSize.y) / 2.0f; float labelX = x + 5.f; float slideX = w / 100.f * 35.f; float marginY = 2; if (val < min) val = min; if (val > max) val = max; // draw label PPGraphics::Get()->DrawText(label, x + labelX, y + labelY, 0.5f, 0.5f, RGB(26, 26, 26), false); // draw bg float startX = x + slideX; float startY = y + marginY; w = w - slideX; h = h - 2 * marginY; PPGraphics::Get()->DrawRectangle(startX, startY, w, h, PPGraphics::Get()->PrimaryDarkColor); char valBuffer[50]; snprintf(valBuffer, sizeof valBuffer, "%.1f", val, val); Vector2 valSize = PPGraphics::Get()->GetTextSize(valBuffer, 0.5f, 0.5f); float valueX = (w - valSize.x) / 2.0f; float valueY = (h - valSize.y) / 2.0f; // draw value PPGraphics::Get()->DrawText(valBuffer, startX + valueX, startY + valueY, 0.5f, 0.5f, PPGraphics::Get()->AccentTextColor, false); float newValue = val; // draw plus and minus button if(RepeatButton(startX + 1, startY + 1, 30 - 2, h - 2, "<", RGB(236, 240, 241), RGB(189, 195, 199), RGB(44, 62, 80))) { // minus newValue -= step; } if(RepeatButton(startX + w - 30, startY + 1, 30 - 1, h - 2, ">", RGB(236, 240, 241), RGB(189, 195, 199), RGB(44, 62, 80))) { // plus newValue += step; } if (newValue < min) newValue = min; if (newValue > max) newValue = max; return newValue; } /////////////////////////////////////////////////////////////////////////// // CHECKBOX /////////////////////////////////////////////////////////////////////////// bool PPUI::ToggleBox(float x, float y, float w, float h, bool value, const char* label) { Vector2 tSize = PPGraphics::Get()->GetTextSize(label, 0.5f, 0.5f); float labelY = (h - tSize.y) / 2.0f; float labelX = x + 5.f; float boxSize = (w / 100.f * 35.f); float marginX = w - boxSize; float marginY = 2; // draw label PPGraphics::Get()->DrawText(label, x + labelX, y + labelY, 0.5f, 0.5f, RGB(26, 26, 26), false); // draw bg float startX = x + marginX; float startY = y + marginY; w = w - marginX; h = h - 2 * marginY; PPGraphics::Get()->DrawRectangle(startX, startY, w, h, PPGraphics::Get()->PrimaryDarkColor); bool result = value; if(value) { // on button FlatColorButton(startX + 1, startY + 1, (boxSize / 2) - 2, h - 2, "On", RGB(236, 240, 241), RGB(189, 195, 199), RGB(44, 62, 80)); // off button if (FlatColorButton(startX + 1 + (boxSize / 2), startY + 1, (boxSize / 2) - 2, h - 2, "Off", PPGraphics::Get()->PrimaryDarkColor, PPGraphics::Get()->PrimaryColor, RGB(236, 240, 241))) { if(!mTmpLockTouch) result = false; } }else { // on button if (FlatColorButton(startX + 1, startY + 1, (boxSize / 2) - 2, h - 2, "On", PPGraphics::Get()->PrimaryDarkColor, PPGraphics::Get()->PrimaryColor, RGB(236, 240, 241))) { if (!mTmpLockTouch) result = true; } // off button FlatColorButton(startX + 1 + (boxSize / 2), startY + 1, (boxSize / 2) - 2, h - 2, "Off", RGB(236, 240, 241), RGB(189, 195, 199), RGB(44, 62, 80)); } return result; } bool PPUI::SelectBox(float x, float y, float w, float h, Color color, float rounding) { PPGraphics::Get()->DrawRectangle(x, y, w, h, color, rounding); return TouchUpOnArea(x, y, w, h) && !mTmpLockTouch; } /////////////////////////////////////////////////////////////////////////// // BUTTON /////////////////////////////////////////////////////////////////////////// bool PPUI::FlatButton(float x, float y, float w, float h, const char* label, float rounding) { return FlatColorButton(x, y, w, h, label, RGB(26, 188, 156), RGB(46, 204, 113), RGB(236, 240, 241), rounding); } bool PPUI::FlatDarkButton(float x, float y, float w, float h, const char* label, float rounding) { return FlatColorButton(x, y, w, h, label, RGB(22, 160, 133), RGB(39, 174, 96), RGB(236, 240, 241), rounding); } bool PPUI::FlatColorButton(float x, float y, float w, float h, const char* label, Color colNormal, Color colActive, Color txtCol, float rounding) { float tScale = 0.5f; if (TouchDownOnArea(x, y, w, h) && !mTmpLockTouch) { PPGraphics::Get()->DrawRectangle(x, y, w, h, colActive, rounding); tScale = 0.6f; } else { PPGraphics::Get()->DrawRectangle(x, y, w, h, colNormal, rounding); } Vector2 tSize = PPGraphics::Get()->GetTextSize(label, tScale, tScale); PPGraphics::Get()->DrawText(label, x + (w - tSize.x) / 2.0f, y + (h - tSize.y) / 2.0f, tScale, tScale, txtCol, false); return TouchUpOnArea(x, y, w, h) && !mTmpLockTouch; } bool PPUI::RepeatButton(float x, float y, float w, float h, const char* label, Color colNormal, Color colActive, Color txtCol) { bool isTouchDown = TouchDownOnArea(x, y, w, h); float tScale = 0.5f; u64 difTime = 0; if (isTouchDown && !mTmpLockTouch) { PPGraphics::Get()->DrawRectangle(x, y, w, h, colActive); tScale = 0.6f; if (holdTime == 0) { holdTime = osGetTime(); }else { difTime = osGetTime() - holdTime; } } else { PPGraphics::Get()->DrawRectangle(x, y, w, h, colNormal); } Vector2 tSize = PPGraphics::Get()->GetTextSize(label, tScale, tScale); float startX = (w - tSize.x) / 2.0f; float startY = (h - tSize.y) / 2.0f; PPGraphics::Get()->DrawText(label, x + startX, y + startY, tScale, tScale, txtCol, false); return (isTouchDown && difTime > 500 || TouchUpOnArea(x, y, w, h)) && !mTmpLockTouch; } /////////////////////////////////////////////////////////////////////////// // TEXT /////////////////////////////////////////////////////////////////////////// /** * \brief Draw label box * \param x * \param y * \param w * \param h * \param defaultValue * \param placeHolder */ int PPUI::LabelBox(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale, float rounding) { PPGraphics::Get()->DrawRectangle(x, y, w, h, bgColor, rounding); Vector2 tSize = PPGraphics::Get()->GetTextSize(label, scale, scale); float startX = (w - tSize.x) / 2.0f; float startY = (h - tSize.y) / 2.0f; PPGraphics::Get()->DrawText(label, x + startX, y + startY, scale, scale, txtColor, false); #ifdef UI_DEBUG char buffer[100]; snprintf(buffer, sizeof buffer, "w:%.02f|h:%.02f", tSize.x, tSize.y); PPGraphics::Get()->DrawText(buffer, x , y - 10, 0.8f * scale, 0.8f * scale, txtColor, false); #endif return TouchUpOnArea(x, y, w, h) && !mTmpLockTouch; } int PPUI::LabelBoxAutoWrap(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale, float rounding) { PPGraphics::Get()->DrawRectangle(x, y, w, h, bgColor, rounding); Vector3 tSize = PPGraphics::Get()->GetTextSizeAutoWrap(label, scale, scale, w); float startX = (w - tSize.x) / 2.0f; float startY = (h - tSize.y) / 2.0f; PPGraphics::Get()->DrawTextAutoWrap(label, x + startX, y + startY, w, scale, scale, txtColor, false); #ifdef UI_DEBUG char buffer[100]; snprintf(buffer, sizeof buffer, "w:%.02f|h:%.02f|l:%d", tSize.x, tSize.y, tSize.z); PPGraphics::Get()->DrawText(buffer, x, y - 10, 0.8f * scale, 0.8f * scale, txtColor, false); #endif return TouchUpOnArea(x, y, w, h) && !mTmpLockTouch; } int PPUI::LabelBoxLeft(float x, float y, float w, float h, const char* label, Color bgColor, Color txtColor, float scale, float rounding) { PPGraphics::Get()->DrawRectangle(x, y, w, h, bgColor, rounding); Vector2 tSize = PPGraphics::Get()->GetTextSize(label, scale, scale); float startY = (h - tSize.y) / 2.0f; PPGraphics::Get()->DrawText(label, x, y + startY, scale, scale, txtColor, false); #ifdef UI_DEBUG char buffer[100]; snprintf(buffer, sizeof buffer, "w:%.02f|h:%.02f", tSize.x, tSize.y); PPGraphics::Get()->DrawText(buffer, x, y - 10, 0.8f * scale, 0.8f * scale, txtColor, false); #endif return TouchUpOnArea(x, y, w, h) && !mTmpLockTouch; } /////////////////////////////////////////////////////////////////////////// // POPUP /////////////////////////////////////////////////////////////////////////// bool PPUI::HasPopup() { return mPopupList.size() > 0; } PopupCallback PPUI::GetPopup() { return mPopupList[mPopupList.size() - 1]; } void PPUI::ClosePopup() { mPopupList.erase(mPopupList.end() - 1); } void PPUI::AddPopup(PopupCallback callback) { mPopupList.push_back(callback); } ================================================ FILE: PinBox/PinBox/source/easing.cpp ================================================ #include #include #include "easing.h" #ifndef PI #define PI 3.1415926545 #endif double easeInSine( double t ) { return sin( 1.5707963 * t ); } double easeOutSine( double t ) { return 1 + sin( 1.5707963 * (--t) ); } double easeInOutSine( double t ) { return 0.5 * (1 + sin( 3.1415926 * (t - 0.5) ) ); } double easeInQuad( double t ) { return t * t; } double easeOutQuad( double t ) { return t * (2 - t); } double easeInOutQuad( double t ) { return t < 0.5 ? 2 * t * t : t * (4 - 2 * t) - 1; } double easeInCubic( double t ) { return t * t * t; } double easeOutCubic( double t ) { return 1 + (--t) * t * t; } double easeInOutCubic( double t ) { return t < 0.5 ? 4 * t * t * t : 1 + (--t) * (2 * (--t)) * (2 * t); } double easeInQuart( double t ) { t *= t; return t * t; } double easeOutQuart( double t ) { t = (--t) * t; return 1 - t * t; } double easeInOutQuart( double t ) { if( t < 0.5 ) { t *= t; return 8 * t * t; } else { t = (--t) * t; return 1 - 8 * t * t; } } double easeInQuint( double t ) { double t2 = t * t; return t * t2 * t2; } double easeOutQuint( double t ) { double t2 = (--t) * t; return 1 + t * t2 * t2; } double easeInOutQuint( double t ) { double t2; if( t < 0.5 ) { t2 = t * t; return 16 * t * t2 * t2; } else { t2 = (--t) * t; return 1 + 16 * t * t2 * t2; } } double easeInExpo( double t ) { return (pow( 2, 8 * t ) - 1) / 255; } double easeOutExpo( double t ) { return 1 - pow( 2, -8 * t ); } double easeInOutExpo( double t ) { if( t < 0.5 ) { return (pow( 2, 16 * t ) - 1) / 510; } else { return 1 - 0.5 * pow( 2, -16 * (t - 0.5) ); } } double easeInCirc( double t ) { return 1 - sqrt( 1 - t ); } double easeOutCirc( double t ) { return sqrt( t ); } double easeInOutCirc( double t ) { if( t < 0.5 ) { return (1 - sqrt( 1 - 2 * t )) * 0.5; } else { return (1 + sqrt( 2 * t - 1 )) * 0.5; } } double easeInBack( double t ) { return t * t * (2.70158 * t - 1.70158); } double easeOutBack( double t ) { return 1 + (--t) * t * (2.70158 * t + 1.70158); } double easeInOutBack( double t ) { if( t < 0.5 ) { return t * t * (7 * t - 2.5) * 2; } else { return 1 + (--t) * t * 2 * (7 * t + 2.5); } } double easeInElastic( double t ) { double t2 = t * t; return t2 * t2 * sin( t * PI * 4.5 ); } double easeOutElastic( double t ) { double t2 = (t - 1) * (t - 1); return 1 - t2 * t2 * cos( t * PI * 4.5 ); } double easeInOutElastic( double t ) { double t2; if( t < 0.45 ) { t2 = t * t; return 8 * t2 * t2 * sin( t * PI * 9 ); } else if( t < 0.55 ) { return 0.5 + 0.75 * sin( t * PI * 4 ); } else { t2 = (t - 1) * (t - 1); return 1 - 8 * t2 * t2 * sin( t * PI * 9 ); } } double easeInBounce( double t ) { return pow( 2, 6 * (t - 1) ) * abs( sin( t * PI * 3.5 ) ); } double easeOutBounce( double t ) { return 1 - pow( 2, -6 * t ) * abs( cos( t * PI * 3.5 ) ); } double easeInOutBounce( double t ) { if( t < 0.5 ) { return 8 * pow( 2, 8 * (t - 1) ) * abs( sin( t * PI * 7 ) ); } else { return 1 - 8 * pow( 2, -8 * t ) * abs( sin( t * PI * 7 ) ); } } easingFunction getEasingFunction( easing_functions function ) { static std::map< easing_functions, easingFunction > easingFunctions; if( easingFunctions.empty() ) { easingFunctions.insert( std::make_pair( EaseInSine, easeInSine ) ); easingFunctions.insert( std::make_pair( EaseOutSine, easeOutSine ) ); easingFunctions.insert( std::make_pair( EaseInOutSine, easeInOutSine ) ); easingFunctions.insert( std::make_pair( EaseInQuad, easeInQuad ) ); easingFunctions.insert( std::make_pair( EaseOutQuad, easeOutQuad ) ); easingFunctions.insert( std::make_pair( EaseInOutQuad, easeInOutQuad ) ); easingFunctions.insert( std::make_pair( EaseInCubic, easeInCubic ) ); easingFunctions.insert( std::make_pair( EaseOutCubic, easeOutCubic ) ); easingFunctions.insert( std::make_pair( EaseInOutCubic, easeInOutCubic ) ); easingFunctions.insert( std::make_pair( EaseInQuart, easeInQuart ) ); easingFunctions.insert( std::make_pair( EaseOutQuart, easeOutQuart ) ); easingFunctions.insert( std::make_pair( EaseInOutQuart, easeInOutQuart) ); easingFunctions.insert( std::make_pair( EaseInQuint, easeInQuint ) ); easingFunctions.insert( std::make_pair( EaseOutQuint, easeOutQuint ) ); easingFunctions.insert( std::make_pair( EaseInOutQuint, easeInOutQuint ) ); easingFunctions.insert( std::make_pair( EaseInExpo, easeInExpo ) ); easingFunctions.insert( std::make_pair( EaseOutExpo, easeOutExpo ) ); easingFunctions.insert( std::make_pair( EaseInOutExpo, easeInOutExpo ) ); easingFunctions.insert( std::make_pair( EaseInCirc, easeInCirc ) ); easingFunctions.insert( std::make_pair( EaseOutCirc, easeOutCirc ) ); easingFunctions.insert( std::make_pair( EaseInOutCirc, easeInOutCirc ) ); easingFunctions.insert( std::make_pair( EaseInBack, easeInBack ) ); easingFunctions.insert( std::make_pair( EaseOutBack, easeOutBack ) ); easingFunctions.insert( std::make_pair( EaseInOutBack, easeInOutBack ) ); easingFunctions.insert( std::make_pair( EaseInElastic, easeInElastic ) ); easingFunctions.insert( std::make_pair( EaseOutElastic, easeOutElastic ) ); easingFunctions.insert( std::make_pair( EaseInOutElastic, easeInOutElastic ) ); easingFunctions.insert( std::make_pair( EaseInBounce, easeInBounce ) ); easingFunctions.insert( std::make_pair( EaseOutBounce, easeOutBounce ) ); easingFunctions.insert( std::make_pair( EaseInOutBounce, easeInOutBounce ) ); } auto it = easingFunctions.find( function ); return it == easingFunctions.end() ? nullptr : it->second; } ================================================ FILE: PinBox/PinBox/source/lodepng.cpp ================================================ /* LodePNG version 20180819 Copyright (c) 2005-2018 Lode Vandevenne This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* The manual and changelog are in the header file "lodepng.h" Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for C. */ #include "lodepng.h" #include #include #include #if defined(_MSC_VER) && (_MSC_VER >= 1310) /*Visual Studio: A few warning types are not desired here.*/ #pragma warning( disable : 4244 ) /*implicit conversions: not warned by gcc -Wall -Wextra and requires too much casts*/ #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ #endif /*_MSC_VER */ const char* LODEPNG_VERSION_STRING = "20180819"; /* This source file is built up in the following large parts. The code sections with the "LODEPNG_COMPILE_" #defines divide this up further in an intermixed way. -Tools for C and common code for PNG and Zlib -C Code for Zlib (huffman, deflate, ...) -C Code for PNG (file format chunks, adam7, PNG filters, color conversions, ...) -The C++ wrapper around all of the above */ /*The malloc, realloc and free functions defined here with "lodepng_" in front of the name, so that you can easily change them to others related to your platform if needed. Everything else in the code calls these. Pass -DLODEPNG_NO_COMPILE_ALLOCATORS to the compiler, or comment out #define LODEPNG_COMPILE_ALLOCATORS in the header, to disable the ones here and define them in your own project's source files without needing to change lodepng source code. Don't forget to remove "static" if you copypaste them from here.*/ #ifdef LODEPNG_COMPILE_ALLOCATORS static void* lodepng_malloc(size_t size) { #ifdef LODEPNG_MAX_ALLOC if (size > LODEPNG_MAX_ALLOC) return 0; #endif return malloc(size); } static void* lodepng_realloc(void* ptr, size_t new_size) { #ifdef LODEPNG_MAX_ALLOC if (new_size > LODEPNG_MAX_ALLOC) return 0; #endif return realloc(ptr, new_size); } static void lodepng_free(void* ptr) { free(ptr); } #else /*LODEPNG_COMPILE_ALLOCATORS*/ void* lodepng_malloc(size_t size); void* lodepng_realloc(void* ptr, size_t new_size); void lodepng_free(void* ptr); #endif /*LODEPNG_COMPILE_ALLOCATORS*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // Tools for C, and common code for PNG and Zlib. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #define LODEPNG_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define LODEPNG_MIN(a, b) (((a) < (b)) ? (a) : (b)) /* Often in case of an error a value is assigned to a variable and then it breaks out of a loop (to go to the cleanup phase of a function). This macro does that. It makes the error handling code shorter and more readable. Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); */ #define CERROR_BREAK(errorvar, code)\ {\ errorvar = code;\ break;\ } /*version of CERROR_BREAK that assumes the common case where the error variable is named "error"*/ #define ERROR_BREAK(code) CERROR_BREAK(error, code) /*Set error var to the error code, and return it.*/ #define CERROR_RETURN_ERROR(errorvar, code)\ {\ errorvar = code;\ return code;\ } /*Try the code, if it returns error, also return the error.*/ #define CERROR_TRY_RETURN(call)\ {\ unsigned error = call;\ if(error) return error;\ } /*Set error var to the error code, and return from the void function.*/ #define CERROR_RETURN(errorvar, code)\ {\ errorvar = code;\ return;\ } /* About uivector, ucvector and string: -All of them wrap dynamic arrays or text strings in a similar way. -LodePNG was originally written in C++. The vectors replace the std::vectors that were used in the C++ version. -The string tools are made to avoid problems with compilers that declare things like strncat as deprecated. -They're not used in the interface, only internally in this file as static functions. -As with many other structs in this file, the init and cleanup functions serve as ctor and dtor. */ #ifdef LODEPNG_COMPILE_ZLIB /*dynamic vector of unsigned ints*/ typedef struct uivector { unsigned* data; size_t size; /*size in number of unsigned longs*/ size_t allocsize; /*allocated size in bytes*/ } uivector; static void uivector_cleanup(void* p) { ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; lodepng_free(((uivector*)p)->data); ((uivector*)p)->data = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_reserve(uivector* p, size_t allocsize) { if (allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = lodepng_realloc(p->data, newsize); if (data) { p->allocsize = newsize; p->data = (unsigned*)data; } else return 0; /*error: not enough memory*/ } return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_resize(uivector* p, size_t size) { if (!uivector_reserve(p, size * sizeof(unsigned))) return 0; p->size = size; return 1; /*success*/ } /*resize and give all new elements the value*/ static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) { size_t oldsize = p->size, i; if (!uivector_resize(p, size)) return 0; for (i = oldsize; i < size; ++i) p->data[i] = value; return 1; } static void uivector_init(uivector* p) { p->data = NULL; p->size = p->allocsize = 0; } #ifdef LODEPNG_COMPILE_ENCODER /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned uivector_push_back(uivector* p, unsigned c) { if (!uivector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ /* /////////////////////////////////////////////////////////////////////////// */ /*dynamic vector of unsigned chars*/ typedef struct ucvector { unsigned char* data; size_t size; /*used size*/ size_t allocsize; /*allocated size*/ } ucvector; /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_reserve(ucvector* p, size_t allocsize) { if (allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = lodepng_realloc(p->data, newsize); if (data) { p->allocsize = newsize; p->data = (unsigned char*)data; } else return 0; /*error: not enough memory*/ } return 1; } /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_resize(ucvector* p, size_t size) { if (!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; p->size = size; return 1; /*success*/ } #ifdef LODEPNG_COMPILE_PNG static void ucvector_cleanup(void* p) { ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; lodepng_free(((ucvector*)p)->data); ((ucvector*)p)->data = NULL; } static void ucvector_init(ucvector* p) { p->data = NULL; p->size = p->allocsize = 0; } #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ZLIB /*you can both convert from vector to buffer&size and vica versa. If you use init_buffer to take over a buffer and size, it is not needed to use cleanup*/ static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) { p->data = buffer; p->allocsize = p->size = size; } #endif /*LODEPNG_COMPILE_ZLIB*/ #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) /*returns 1 if success, 0 if failure ==> nothing done*/ static unsigned ucvector_push_back(ucvector* p, unsigned char c) { if (!ucvector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*free string pointer and set it to NULL*/ static void string_cleanup(char** out) { lodepng_free(*out); *out = NULL; } /* dynamically allocates a new string with a copy of the null terminated input text */ static char* alloc_string(const char* in) { size_t insize = strlen(in); char* out = (char*)lodepng_malloc(insize + 1); if (out) { size_t i; for (i = 0; i != insize; ++i) { out[i] = in[i]; } out[i] = 0; } return out; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_PNG*/ /* ////////////////////////////////////////////////////////////////////////// */ unsigned lodepng_read32bitInt(const unsigned char* buffer) { return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); } #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) /*buffer must have at least 4 allocated bytes available*/ static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) { buffer[0] = (unsigned char)((value >> 24) & 0xff); buffer[1] = (unsigned char)((value >> 16) & 0xff); buffer[2] = (unsigned char)((value >> 8) & 0xff); buffer[3] = (unsigned char)((value) & 0xff); } #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ #ifdef LODEPNG_COMPILE_ENCODER static void lodepng_add32bitInt(ucvector* buffer, unsigned value) { ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); } #endif /*LODEPNG_COMPILE_ENCODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / File IO / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DISK /* returns negative value on error. This should be pure C compatible, so no fstat. */ static long lodepng_filesize(const char* filename) { FILE* file; long size; file = fopen(filename, "rb"); if (!file) return -1; if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return -1; } size = ftell(file); /* It may give LONG_MAX as directory size, this is invalid for us. */ if (size == LONG_MAX) size = -1; fclose(file); return size; } /* load file into buffer that already has the correct allocated size. Returns error code.*/ static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) { FILE* file; size_t readsize; file = fopen(filename, "rb"); if (!file) return 78; readsize = fread(out, 1, size, file); fclose(file); if (readsize != size) return 78; return 0; } unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { long size = lodepng_filesize(filename); if (size < 0) return 78; *outsize = (size_t)size; *out = (unsigned char*)lodepng_malloc((size_t)size); if (!(*out) && size > 0) return 83; /*the above malloc failed*/ return lodepng_buffer_file(*out, (size_t)size, filename); } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { FILE* file; file = fopen(filename, "wb"); if (!file) return 79; fwrite((char*)buffer, 1, buffersize, file); fclose(file); return 0; } #endif /*LODEPNG_COMPILE_DISK*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // End of common code and tools. Begin of Zlib related code. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_ENCODER /*TODO: this ignores potential out of memory errors*/ #define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\ {\ /*add a new byte at the end*/\ if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\ /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\ (bitstream->data[bitstream->size - 1]) |= (bit << ((*bitpointer) & 0x7));\ ++(*bitpointer);\ } static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for (i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); } static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for (i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); } #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DECODER #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); ++(*bitpointer); return result; } static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0, i; for (i = 0; i != nbits; ++i) { result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; ++(*bitpointer); } return result; } #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / Deflate - Huffman / */ /* ////////////////////////////////////////////////////////////////////////// */ #define FIRST_LENGTH_CODE_INDEX 257 #define LAST_LENGTH_CODE_INDEX 285 /*256 literals, the end code, some length codes, and 2 unused codes*/ #define NUM_DEFLATE_CODE_SYMBOLS 288 /*the distance codes have their own symbols, 30 used, 2 unused*/ #define NUM_DISTANCE_SYMBOLS 32 /*the code length codes. 0-15: code lengths, 16: copy previous 3-6 times, 17: 3-10 zeros, 18: 11-138 zeros*/ #define NUM_CODE_LENGTH_CODES 19 /*the base lengths represented by codes 257-285*/ static const unsigned LENGTHBASE[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; /*the extra bits used by codes 257-285 (added to base length)*/ static const unsigned LENGTHEXTRA[29] = { 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 }; /*the base backwards distances (the bits of distance codes appear after length codes and use their own huffman tree)*/ static const unsigned DISTANCEBASE[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; /*the extra bits of backwards distances (added to base)*/ static const unsigned DISTANCEEXTRA[30] = { 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 }; /*the order in which "code length alphabet code lengths" are stored, out of this the huffman tree of the dynamic huffman tree lengths is generated*/ static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; /* ////////////////////////////////////////////////////////////////////////// */ /* Huffman tree struct, containing multiple representations of the tree */ typedef struct HuffmanTree { unsigned* tree2d; unsigned* tree1d; unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ unsigned maxbitlen; /*maximum number of bits a single code can get*/ unsigned numcodes; /*number of symbols in the alphabet = number of codes*/ } HuffmanTree; /*function used for debug purposes to draw the tree in ascii art with C++*/ /* static void HuffmanTree_draw(HuffmanTree* tree) { std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; for(size_t i = 0; i != tree->tree1d.size; ++i) { if(tree->lengths.data[i]) std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; } std::cout << std::endl; }*/ static void HuffmanTree_init(HuffmanTree* tree) { tree->tree2d = 0; tree->tree1d = 0; tree->lengths = 0; } static void HuffmanTree_cleanup(HuffmanTree* tree) { lodepng_free(tree->tree2d); lodepng_free(tree->tree1d); lodepng_free(tree->lengths); } /*the tree representation used by the decoder. return value is error*/ static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) { unsigned nodefilled = 0; /*up to which node it is filled*/ unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ unsigned n, i; tree->tree2d = (unsigned*)lodepng_malloc(tree->numcodes * 2 * sizeof(unsigned)); if (!tree->tree2d) return 83; /*alloc fail*/ /* convert tree1d[] to tree2d[][]. In the 2D array, a value of 32767 means uninited, a value >= numcodes is an address to another bit, a value < numcodes is a code. The 2 rows are the 2 possible bit values (0 or 1), there are as many columns as codes - 1. A good huffman tree has N * 2 - 1 nodes, of which N - 1 are internal nodes. Here, the internal nodes are stored (what their 0 and 1 option point to). There is only memory for such good tree currently, if there are more nodes (due to too long length codes), error 55 will happen */ for (n = 0; n < tree->numcodes * 2; ++n) { tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ } for (n = 0; n < tree->numcodes; ++n) /*the codes*/ { for (i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ { unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); /*oversubscribed, see comment in lodepng_error_text*/ if (treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; if (tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ { if (i + 1 == tree->lengths[n]) /*last bit*/ { tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ treepos = 0; } else { /*put address of the next step in here, first that address has to be found of course (it's just nodefilled + 1)...*/ ++nodefilled; /*addresses encoded with numcodes added to it*/ tree->tree2d[2 * treepos + bit] = nodefilled + tree->numcodes; treepos = nodefilled; } } else treepos = tree->tree2d[2 * treepos + bit] - tree->numcodes; } } for (n = 0; n < tree->numcodes * 2; ++n) { if (tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ } return 0; } /* Second step for the ...makeFromLengths and ...makeFromFrequencies functions. numcodes, lengths and maxbitlen must already be filled in correctly. return value is error. */ static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { uivector blcount; uivector nextcode; unsigned error = 0; unsigned bits, n; uivector_init(&blcount); uivector_init(&nextcode); tree->tree1d = (unsigned*)lodepng_malloc(tree->numcodes * sizeof(unsigned)); if (!tree->tree1d) error = 83; /*alloc fail*/ if (!uivector_resizev(&blcount, tree->maxbitlen + 1, 0) || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) error = 83; /*alloc fail*/ if (!error) { /*step 1: count number of instances of each code length*/ for (bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; /*step 2: generate the nextcode values*/ for (bits = 1; bits <= tree->maxbitlen; ++bits) { nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; } /*step 3: generate all the codes*/ for (n = 0; n != tree->numcodes; ++n) { if (tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; } } uivector_cleanup(&blcount); uivector_cleanup(&nextcode); if (!error) return HuffmanTree_make2DTree(tree); else return error; } /* given the code lengths (as stored in the PNG file), generate the tree as defined by Deflate. maxbitlen is the maximum bits that a code in the tree can have. return value is error. */ static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, size_t numcodes, unsigned maxbitlen) { unsigned i; tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); if (!tree->lengths) return 83; /*alloc fail*/ for (i = 0; i != numcodes; ++i) tree->lengths[i] = bitlen[i]; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->maxbitlen = maxbitlen; return HuffmanTree_makeFromLengths2(tree); } #ifdef LODEPNG_COMPILE_ENCODER /*BPM: Boundary Package Merge, see "A Fast and Space-Economical Algorithm for Length-Limited Coding", Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ /*chain node for boundary package merge*/ typedef struct BPMNode { int weight; /*the sum of all weights in this chain*/ unsigned index; /*index of this leaf node (called "count" in the paper)*/ struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ int in_use; } BPMNode; /*lists of chains*/ typedef struct BPMLists { /*memory pool*/ unsigned memsize; BPMNode* memory; unsigned numfree; unsigned nextfree; BPMNode** freelist; /*two heads of lookahead chains per list*/ unsigned listsize; BPMNode** chains0; BPMNode** chains1; } BPMLists; /*creates a new chain node with the given parameters, from the memory in the lists */ static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) { unsigned i; BPMNode* result; /*memory full, so garbage collect*/ if (lists->nextfree >= lists->numfree) { /*mark only those that are in use*/ for (i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; for (i = 0; i != lists->listsize; ++i) { BPMNode* node; for (node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; for (node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; } /*collect those that are free*/ lists->numfree = 0; for (i = 0; i != lists->memsize; ++i) { if (!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; } lists->nextfree = 0; } result = lists->freelist[lists->nextfree++]; result->weight = weight; result->index = index; result->tail = tail; return result; } /*sort the leaves with stable mergesort*/ static void bpmnode_sort(BPMNode* leaves, size_t num) { BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); size_t width, counter = 0; for (width = 1; width < num; width *= 2) { BPMNode* a = (counter & 1) ? mem : leaves; BPMNode* b = (counter & 1) ? leaves : mem; size_t p; for (p = 0; p < num; p += 2 * width) { size_t q = (p + width > num) ? num : (p + width); size_t r = (p + 2 * width > num) ? num : (p + 2 * width); size_t i = p, j = q, k; for (k = p; k < r; k++) { if (i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; else b[k] = a[j++]; } } counter++; } if (counter & 1) memcpy(leaves, mem, sizeof(*leaves) * num); lodepng_free(mem); } /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) { unsigned lastindex = lists->chains1[c]->index; if (c == 0) { if (lastindex >= numpresent) return; lists->chains0[c] = lists->chains1[c]; lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); } else { /*sum of the weights of the head nodes of the previous lookahead chains.*/ int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; lists->chains0[c] = lists->chains1[c]; if (lastindex < numpresent && sum > leaves[lastindex].weight) { lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); return; } lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); /*in the end we are only interested in the chain of the last list, so no need to recurse if we're at the last one (this gives measurable speedup)*/ if (num + 1 < (int)(2 * numpresent - 2)) { boundaryPM(lists, leaves, numpresent, c - 1, num); boundaryPM(lists, leaves, numpresent, c - 1, num); } } } unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; unsigned i; size_t numpresent = 0; /*number of symbols with non-zero frequency*/ BPMNode* leaves; /*the symbols, only those with > 0 frequency*/ if (numcodes == 0) return 80; /*error: a tree of 0 symbols is not supposed to be made*/ if ((1u << maxbitlen) < (unsigned)numcodes) return 80; /*error: represent all symbols*/ leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); if (!leaves) return 83; /*alloc fail*/ for (i = 0; i != numcodes; ++i) { if (frequencies[i] > 0) { leaves[numpresent].weight = (int)frequencies[i]; leaves[numpresent].index = i; ++numpresent; } } for (i = 0; i != numcodes; ++i) lengths[i] = 0; /*ensure at least two present symbols. There should be at least one symbol according to RFC 1951 section 3.2.7. Some decoders incorrectly require two. To make these work as well ensure there are at least two symbols. The Package-Merge code below also doesn't work correctly if there's only one symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ if (numpresent == 0) { lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ } else if (numpresent == 1) { lengths[leaves[0].index] = 1; lengths[leaves[0].index == 0 ? 1 : 0] = 1; } else { BPMLists lists; BPMNode* node; bpmnode_sort(leaves, numpresent); lists.listsize = maxbitlen; lists.memsize = 2 * maxbitlen * (maxbitlen + 1); lists.nextfree = 0; lists.numfree = lists.memsize; lists.memory = (BPMNode*)lodepng_malloc(lists.memsize * sizeof(*lists.memory)); lists.freelist = (BPMNode**)lodepng_malloc(lists.memsize * sizeof(BPMNode*)); lists.chains0 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); if (!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ if (!error) { for (i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; bpmnode_create(&lists, leaves[0].weight, 1, 0); bpmnode_create(&lists, leaves[1].weight, 2, 0); for (i = 0; i != lists.listsize; ++i) { lists.chains0[i] = &lists.memory[0]; lists.chains1[i] = &lists.memory[1]; } /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ for (i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); for (node = lists.chains1[maxbitlen - 1]; node; node = node->tail) { for (i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; } } lodepng_free(lists.memory); lodepng_free(lists.freelist); lodepng_free(lists.chains0); lodepng_free(lists.chains1); } lodepng_free(leaves); return error; } /*Create the Huffman tree given the symbol frequencies*/ static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; while (!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ tree->maxbitlen = maxbitlen; tree->numcodes = (unsigned)numcodes; /*number of symbols*/ tree->lengths = (unsigned*)lodepng_realloc(tree->lengths, numcodes * sizeof(unsigned)); if (!tree->lengths) return 83; /*alloc fail*/ /*initialize all lengths to 0*/ memset(tree->lengths, 0, numcodes * sizeof(unsigned)); error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen); if (!error) error = HuffmanTree_makeFromLengths2(tree); return error; } static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) { return tree->tree1d[index]; } static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) { return tree->lengths[index]; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ static unsigned generateFixedLitLenTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); if (!bitlen) return 83; /*alloc fail*/ /*288 possible codes: 0-255=literals, 256=endcode, 257-285=lengthcodes, 286-287=unused*/ for (i = 0; i <= 143; ++i) bitlen[i] = 8; for (i = 144; i <= 255; ++i) bitlen[i] = 9; for (i = 256; i <= 279; ++i) bitlen[i] = 7; for (i = 280; i <= 287; ++i) bitlen[i] = 8; error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DEFLATE_CODE_SYMBOLS, 15); lodepng_free(bitlen); return error; } /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ static unsigned generateFixedDistanceTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); if (!bitlen) return 83; /*alloc fail*/ /*there are 32 distance codes, but 30-31 are unused*/ for (i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen[i] = 5; error = HuffmanTree_makeFromLengths(tree, bitlen, NUM_DISTANCE_SYMBOLS, 15); lodepng_free(bitlen); return error; } #ifdef LODEPNG_COMPILE_DECODER /* returns the code, or (unsigned)(-1) if error happened inbitlength is the length of the complete buffer, in bits (so its byte length times 8) */ static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, const HuffmanTree* codetree, size_t inbitlength) { unsigned treepos = 0, ct; for (;;) { if (*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ /* decode the symbol from the tree. The "readBitFromStream" code is inlined in the expression below because this is the biggest bottleneck while decoding */ ct = codetree->tree2d[(treepos << 1) + READBIT(*bp, in)]; ++(*bp); if (ct < codetree->numcodes) return ct; /*the symbol is decoded, return it*/ else treepos = ct - codetree->numcodes; /*symbol not yet decoded, instead move tree position*/ if (treepos >= codetree->numcodes) return (unsigned)(-1); /*error: it appeared outside the codetree*/ } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_DECODER /* ////////////////////////////////////////////////////////////////////////// */ /* / Inflator (Decompressor) / */ /* ////////////////////////////////////////////////////////////////////////// */ /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { /*TODO: check for out of memory errors*/ generateFixedLitLenTree(tree_ll); generateFixedDistanceTree(tree_d); } /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, const unsigned char* in, size_t* bp, size_t inlength) { /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ unsigned error = 0; unsigned n, HLIT, HDIST, HCLEN, i; size_t inbitlength = inlength * 8; /*see comments in deflateDynamic for explanation of the context and these variables, it is analogous*/ unsigned* bitlen_ll = 0; /*lit,len code lengths*/ unsigned* bitlen_d = 0; /*dist code lengths*/ /*code length code lengths ("clcl"), the bit lengths of the huffman tree used to compress bitlen_ll and bitlen_d*/ unsigned* bitlen_cl = 0; HuffmanTree tree_cl; /*the code tree for code length codes (the huffman tree for compressed huffman trees)*/ if ((*bp) + 14 > (inlength << 3)) return 49; /*error: the bit pointer is or will go past the memory*/ /*number of literal/length codes + 257. Unlike the spec, the value 257 is added to it here already*/ HLIT = readBitsFromStream(bp, in, 5) + 257; /*number of distance codes. Unlike the spec, the value 1 is added to it here already*/ HDIST = readBitsFromStream(bp, in, 5) + 1; /*number of code length codes. Unlike the spec, the value 4 is added to it here already*/ HCLEN = readBitsFromStream(bp, in, 4) + 4; if ((*bp) + HCLEN * 3 > (inlength << 3)) return 50; /*error: the bit pointer is or will go past the memory*/ HuffmanTree_init(&tree_cl); while (!error) { /*read the code length codes out of 3 * (amount of code length codes) bits*/ bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); if (!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); for (i = 0; i != NUM_CODE_LENGTH_CODES; ++i) { if (i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ } error = HuffmanTree_makeFromLengths(&tree_cl, bitlen_cl, NUM_CODE_LENGTH_CODES, 7); if (error) break; /*now we can use this tree to read the lengths for the tree that this function will return*/ bitlen_ll = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); bitlen_d = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); if (!bitlen_ll || !bitlen_d) ERROR_BREAK(83 /*alloc fail*/); for (i = 0; i != NUM_DEFLATE_CODE_SYMBOLS; ++i) bitlen_ll[i] = 0; for (i = 0; i != NUM_DISTANCE_SYMBOLS; ++i) bitlen_d[i] = 0; /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ i = 0; while (i < HLIT + HDIST) { unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); if (code <= 15) /*a length code*/ { if (i < HLIT) bitlen_ll[i] = code; else bitlen_d[i - HLIT] = code; ++i; } else if (code == 16) /*repeat previous*/ { unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ unsigned value; /*set value to the previous code*/ if (i == 0) ERROR_BREAK(54); /*can't repeat previous if i is 0*/ if ((*bp + 2) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 2); if (i < HLIT + 1) value = bitlen_ll[i - 1]; else value = bitlen_d[i - HLIT - 1]; /*repeat this value in the next lengths*/ for (n = 0; n < replength; ++n) { if (i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ if (i < HLIT) bitlen_ll[i] = value; else bitlen_d[i - HLIT] = value; ++i; } } else if (code == 17) /*repeat "0" 3-10 times*/ { unsigned replength = 3; /*read in the bits that indicate repeat length*/ if ((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 3); /*repeat this value in the next lengths*/ for (n = 0; n < replength; ++n) { if (i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ if (i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; ++i; } } else if (code == 18) /*repeat "0" 11-138 times*/ { unsigned replength = 11; /*read in the bits that indicate repeat length*/ if ((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 7); /*repeat this value in the next lengths*/ for (n = 0; n < replength; ++n) { if (i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ if (i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; ++i; } } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { if (code == (unsigned)(-1)) { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inbitlength ? 10 : 11; } else error = 16; /*unexisting code, this can never happen*/ break; } } if (error) break; if (bitlen_ll[256] == 0) ERROR_BREAK(64); /*the length of the end code 256 must be larger than 0*/ /*now we've finally got HLIT and HDIST, so generate the code trees, and the function is done*/ error = HuffmanTree_makeFromLengths(tree_ll, bitlen_ll, NUM_DEFLATE_CODE_SYMBOLS, 15); if (error) break; error = HuffmanTree_makeFromLengths(tree_d, bitlen_d, NUM_DISTANCE_SYMBOLS, 15); break; /*end of error-while*/ } lodepng_free(bitlen_cl); lodepng_free(bitlen_ll); lodepng_free(bitlen_d); HuffmanTree_cleanup(&tree_cl); return error; } /*inflate a block with dynamic of fixed Huffman tree*/ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength, unsigned btype) { unsigned error = 0; HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ HuffmanTree tree_d; /*the huffman tree for distance codes*/ size_t inbitlength = inlength * 8; HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); if (btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); else if (btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); while (!error) /*decode all symbols until end reached, breaks at end code*/ { /*code_ll is literal, length or end code*/ unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); if (code_ll <= 255) /*literal symbol*/ { /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ if (!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); out->data[*pos] = (unsigned char)code_ll; ++(*pos); } else if (code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ { unsigned code_d, distance; unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ size_t start, forward, backward, length; /*part 1: get length base*/ length = LENGTHBASE[code_ll - FIRST_LENGTH_CODE_INDEX]; /*part 2: get extra bits and add the value of that to length*/ numextrabits_l = LENGTHEXTRA[code_ll - FIRST_LENGTH_CODE_INDEX]; if ((*bp + numextrabits_l) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ length += readBitsFromStream(bp, in, numextrabits_l); /*part 3: get distance code*/ code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); if (code_d > 29) { if (code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inlength * 8 ? 10 : 11; } else error = 18; /*error: invalid distance code (30-31 are never used)*/ break; } distance = DISTANCEBASE[code_d]; /*part 4: get extra bits from distance*/ numextrabits_d = DISTANCEEXTRA[code_d]; if ((*bp + numextrabits_d) > inbitlength) ERROR_BREAK(51); /*error, bit pointer will jump past memory*/ distance += readBitsFromStream(bp, in, numextrabits_d); /*part 5: fill in all the out[n] values based on the length and dist*/ start = (*pos); if (distance > start) ERROR_BREAK(52); /*too long backward distance*/ backward = start - distance; if (!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); if (distance < length) { for (forward = 0; forward < length; ++forward) { out->data[(*pos)++] = out->data[backward++]; } } else { memcpy(out->data + *pos, out->data + backward, length); *pos += length; } } else if (code_ll == 256) { break; /*end code, break the loop*/ } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = ((*bp) > inlength * 8) ? 10 : 11; break; } } HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) { size_t p; unsigned LEN, NLEN, n, error = 0; /*go to first boundary of byte*/ while (((*bp) & 0x7) != 0) ++(*bp); p = (*bp) / 8; /*byte position*/ /*read LEN (2 bytes) and NLEN (2 bytes)*/ if (p + 4 >= inlength) return 52; /*error, bit pointer will jump past memory*/ LEN = in[p] + 256u * in[p + 1]; p += 2; NLEN = in[p] + 256u * in[p + 1]; p += 2; /*check if 16-bit NLEN is really the one's complement of LEN*/ if (LEN + NLEN != 65535) return 21; /*error: NLEN is not one's complement of LEN*/ if (!ucvector_resize(out, (*pos) + LEN)) return 83; /*alloc fail*/ /*read the literal data: LEN bytes are now stored in the out buffer*/ if (p + LEN > inlength) return 23; /*error: reading outside of in buffer*/ for (n = 0; n < LEN; ++n) out->data[(*pos)++] = in[p++]; (*bp) = p * 8; return error; } static unsigned lodepng_inflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ size_t bp = 0; unsigned BFINAL = 0; size_t pos = 0; /*byte position in the out buffer*/ unsigned error = 0; (void)settings; while (!BFINAL) { unsigned BTYPE; if (bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ BFINAL = readBitFromStream(&bp, in); BTYPE = 1u * readBitFromStream(&bp, in); BTYPE += 2u * readBitFromStream(&bp, in); if (BTYPE == 3) return 20; /*error: invalid BTYPE*/ else if (BTYPE == 0) error = inflateNoCompression(out, in, &bp, &pos, insize); /*no compression*/ else error = inflateHuffmanBlock(out, in, &bp, &pos, insize, BTYPE); /*compression, BTYPE 01 or 10*/ if (error) return error; } return error; } unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); error = lodepng_inflatev(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } static unsigned inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if (settings->custom_inflate) { return settings->custom_inflate(out, outsize, in, insize, settings); } else { return lodepng_inflate(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER /* ////////////////////////////////////////////////////////////////////////// */ /* / Deflator (Compressor) / */ /* ////////////////////////////////////////////////////////////////////////// */ static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; /*bitlen is the size in bits of the code*/ static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) { addBitsToStreamReversed(bp, compressed, code, bitlen); } /*search the index in the array, that has the largest value smaller than or equal to the given value, given array must be sorted (if no value is smaller, it returns the size of the given array)*/ static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ size_t left = 1; size_t right = array_size - 1; while (left <= right) { size_t mid = (left + right) >> 1; if (array[mid] >= value) right = mid - 1; else left = mid + 1; } if (left >= array_size || array[left] > value) left--; return left; } static void addLengthDistance(uivector* values, size_t length, size_t distance) { /*values in encoded vector are those used by deflate: 0-255: literal bytes 256: end 257-285: length/distance pair (length code, followed by extra length bits, distance code, extra distance bits) 286-287: invalid*/ unsigned length_code = (unsigned)searchCodeIndex(LENGTHBASE, 29, length); unsigned extra_length = (unsigned)(length - LENGTHBASE[length_code]); unsigned dist_code = (unsigned)searchCodeIndex(DISTANCEBASE, 30, distance); unsigned extra_distance = (unsigned)(distance - DISTANCEBASE[dist_code]); uivector_push_back(values, length_code + FIRST_LENGTH_CODE_INDEX); uivector_push_back(values, extra_length); uivector_push_back(values, dist_code); uivector_push_back(values, extra_distance); } /*3 bytes of data get encoded into two bytes. The hash cannot use more than 3 bytes as input because 3 is the minimum match length for deflate*/ static const unsigned HASH_NUM_VALUES = 65536; static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ typedef struct Hash { int* head; /*hash value to head circular pos - can be outdated if went around window*/ /*circular pos to prev circular pos*/ unsigned short* chain; int* val; /*circular pos to hash value*/ /*TODO: do this not only for zeros but for any repeated byte. However for PNG it's always going to be the zeros that dominate, so not important for PNG*/ int* headz; /*similar to head, but for chainz*/ unsigned short* chainz; /*those with same amount of zeros*/ unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ } Hash; static unsigned hash_init(Hash* hash, unsigned windowsize) { unsigned i; hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); hash->chain = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); hash->zeros = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); if (!hash->head || !hash->chain || !hash->val || !hash->headz || !hash->chainz || !hash->zeros) { return 83; /*alloc fail*/ } /*initialize hash table*/ for (i = 0; i != HASH_NUM_VALUES; ++i) hash->head[i] = -1; for (i = 0; i != windowsize; ++i) hash->val[i] = -1; for (i = 0; i != windowsize; ++i) hash->chain[i] = i; /*same value as index indicates uninitialized*/ for (i = 0; i <= MAX_SUPPORTED_DEFLATE_LENGTH; ++i) hash->headz[i] = -1; for (i = 0; i != windowsize; ++i) hash->chainz[i] = i; /*same value as index indicates uninitialized*/ return 0; } static void hash_cleanup(Hash* hash) { lodepng_free(hash->head); lodepng_free(hash->val); lodepng_free(hash->chain); lodepng_free(hash->zeros); lodepng_free(hash->headz); lodepng_free(hash->chainz); } static unsigned getHash(const unsigned char* data, size_t size, size_t pos) { unsigned result = 0; if (pos + 2 < size) { /*A simple shift and xor hash is used. Since the data of PNGs is dominated by zeroes due to the filters, a better hash does not have a significant effect on speed in traversing the chain, and causes more time spend on calculating the hash.*/ result ^= (unsigned)(data[pos + 0] << 0u); result ^= (unsigned)(data[pos + 1] << 4u); result ^= (unsigned)(data[pos + 2] << 8u); } else { size_t amount, i; if (pos >= size) return 0; amount = size - pos; for (i = 0; i != amount; ++i) result ^= (unsigned)(data[pos + i] << (i * 8u)); } return result & HASH_BIT_MASK; } static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) { const unsigned char* start = data + pos; const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; if (end > data + size) end = data + size; data = start; while (data != end && *data == 0) ++data; /*subtracting two addresses returned as 32-bit number (max value is MAX_SUPPORTED_DEFLATE_LENGTH)*/ return (unsigned)(data - start); } /*wpos = pos & (windowsize - 1)*/ static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) { hash->val[wpos] = (int)hashval; if (hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; hash->head[hashval] = (int)wpos; hash->zeros[wpos] = numzeros; if (hash->headz[numzeros] != -1) hash->chainz[wpos] = hash->headz[numzeros]; hash->headz[numzeros] = (int)wpos; } /* LZ77-encode the data. Return value is error code. The input are raw bytes, the output is in the form of unsigned integers with codes representing for example literal bytes, or length/distance pairs. It uses a hash table technique to let it encode faster. When doing LZ77 encoding, a sliding window (of windowsize) is used, and all past bytes in that window can be used as the "dictionary". A brute force search through all possible distances would be slow, and this hash technique is one out of several ways to speed this up. */ static unsigned encodeLZ77(uivector* out, Hash* hash, const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, unsigned minmatch, unsigned nicematch, unsigned lazymatching) { size_t pos; unsigned i, error = 0; /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ unsigned maxchainlength = windowsize >= 8192 ? windowsize : windowsize / 8; unsigned maxlazymatch = windowsize >= 8192 ? MAX_SUPPORTED_DEFLATE_LENGTH : 64; unsigned usezeros = 1; /*not sure if setting it to false for windowsize < 8192 is better or worse*/ unsigned numzeros = 0; unsigned offset; /*the offset represents the distance in LZ77 terminology*/ unsigned length; unsigned lazy = 0; unsigned lazylength = 0, lazyoffset = 0; unsigned hashval; unsigned current_offset, current_length; unsigned prev_offset; const unsigned char *lastptr, *foreptr, *backptr; unsigned hashpos; if (windowsize == 0 || windowsize > 32768) return 60; /*error: windowsize smaller/larger than allowed*/ if ((windowsize & (windowsize - 1)) != 0) return 90; /*error: must be power of two*/ if (nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; for (pos = inpos; pos < insize; ++pos) { size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ unsigned chainlength = 0; hashval = getHash(in, insize, pos); if (usezeros && hashval == 0) { if (numzeros == 0) numzeros = countZeros(in, insize, pos); else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; } else { numzeros = 0; } updateHashChain(hash, wpos, hashval, numzeros); /*the length and offset found for the current position*/ length = 0; offset = 0; hashpos = hash->chain[wpos]; lastptr = &in[insize < pos + MAX_SUPPORTED_DEFLATE_LENGTH ? insize : pos + MAX_SUPPORTED_DEFLATE_LENGTH]; /*search for the longest string*/ prev_offset = 0; for (;;) { if (chainlength++ >= maxchainlength) break; current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize); if (current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ prev_offset = current_offset; if (current_offset > 0) { /*test the next characters*/ foreptr = &in[pos]; backptr = &in[pos - current_offset]; /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ if (numzeros >= 3) { unsigned skip = hash->zeros[hashpos]; if (skip > numzeros) skip = numzeros; backptr += skip; foreptr += skip; } while (foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ { ++backptr; ++foreptr; } current_length = (unsigned)(foreptr - &in[pos]); if (current_length > length) { length = current_length; /*the longest length*/ offset = current_offset; /*the offset that is related to this longest length*/ /*jump out once a length of max length is found (speed gain). This also jumps out if length is MAX_SUPPORTED_DEFLATE_LENGTH*/ if (current_length >= nicematch) break; } } if (hashpos == hash->chain[hashpos]) break; if (numzeros >= 3 && length > numzeros) { hashpos = hash->chainz[hashpos]; if (hash->zeros[hashpos] != numzeros) break; } else { hashpos = hash->chain[hashpos]; /*outdated hash value, happens if particular value was not encountered in whole last window*/ if (hash->val[hashpos] != (int)hashval) break; } } if (lazymatching) { if (!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) { lazy = 1; lazylength = length; lazyoffset = offset; continue; /*try the next byte*/ } if (lazy) { lazy = 0; if (pos == 0) ERROR_BREAK(81); if (length > lazylength + 1) { /*push the previous character as literal*/ if (!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); } else { length = lazylength; offset = lazyoffset; hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ hash->headz[numzeros] = -1; /*idem*/ --pos; } } } if (length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); /*encode it as length/distance pair or literal value*/ if (length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ { if (!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); } else if (length < minmatch || (length == 3 && offset > 4096)) { /*compensate for the fact that longer offsets have more extra bits, a length of only 3 may be not worth it then*/ if (!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); } else { addLengthDistance(out, length, offset); for (i = 1; i < length; ++i) { ++pos; wpos = pos & (windowsize - 1); hashval = getHash(in, insize, pos); if (usezeros && hashval == 0) { if (numzeros == 0) numzeros = countZeros(in, insize, pos); else if (pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; } else { numzeros = 0; } updateHashChain(hash, wpos, hashval, numzeros); } } } /*end of the loop through each character of input*/ return error; } /* /////////////////////////////////////////////////////////////////////////// */ static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) { /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; unsigned datapos = 0; for (i = 0; i != numdeflateblocks; ++i) { unsigned BFINAL, BTYPE, LEN, NLEN; unsigned char firstbyte; BFINAL = (i == numdeflateblocks - 1); BTYPE = 0; firstbyte = (unsigned char)(BFINAL + ((BTYPE & 1) << 1) + ((BTYPE & 2) << 1)); ucvector_push_back(out, firstbyte); LEN = 65535; if (datasize - datapos < 65535) LEN = (unsigned)datasize - datapos; NLEN = 65535 - LEN; ucvector_push_back(out, (unsigned char)(LEN & 255)); ucvector_push_back(out, (unsigned char)(LEN >> 8)); ucvector_push_back(out, (unsigned char)(NLEN & 255)); ucvector_push_back(out, (unsigned char)(NLEN >> 8)); /*Decompressed data*/ for (j = 0; j < 65535 && datapos < datasize; ++j) { ucvector_push_back(out, data[datapos++]); } } return 0; } /* write the lz77-encoded data, which has lit, len and dist codes, to compressed stream using huffman trees. tree_ll: the tree for lit and len codes. tree_d: the tree for distance codes. */ static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { size_t i = 0; for (i = 0; i != lz77_encoded->size; ++i) { unsigned val = lz77_encoded->data[i]; addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); if (val > 256) /*for a length code, 3 more things have to be added*/ { unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; unsigned length_extra_bits = lz77_encoded->data[++i]; unsigned distance_code = lz77_encoded->data[++i]; unsigned distance_index = distance_code; unsigned n_distance_extra_bits = DISTANCEEXTRA[distance_index]; unsigned distance_extra_bits = lz77_encoded->data[++i]; addBitsToStream(bp, out, length_extra_bits, n_length_extra_bits); addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_d, distance_code), HuffmanTree_getLength(tree_d, distance_code)); addBitsToStream(bp, out, distance_extra_bits, n_distance_extra_bits); } } } /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { unsigned error = 0; /* A block is compressed as follows: The PNG data is lz77 encoded, resulting in literal bytes and length/distance pairs. This is then huffman compressed with two huffman trees. One huffman tree is used for the lit and len values ("ll"), another huffman tree is used for the dist values ("d"). These two trees are stored using their code lengths, and to compress even more these code lengths are also run-length encoded and huffman compressed. This gives a huffman tree of code lengths "cl". The code lenghts used to describe this third tree are the code length code lengths ("clcl"). */ /*The lz77 encoded data, represented with integers since there will also be length and distance codes in it*/ uivector lz77_encoded; HuffmanTree tree_ll; /*tree for lit,len values*/ HuffmanTree tree_d; /*tree for distance codes*/ HuffmanTree tree_cl; /*tree for encoding the code lengths representing tree_ll and tree_d*/ uivector frequencies_ll; /*frequency of lit,len codes*/ uivector frequencies_d; /*frequency of dist codes*/ uivector frequencies_cl; /*frequency of code length codes*/ uivector bitlen_lld; /*lit,len,dist code lenghts (int bits), literally (without repeat codes).*/ uivector bitlen_lld_e; /*bitlen_lld encoded with repeat codes (this is a rudemtary run length compression)*/ /*bitlen_cl is the code length code lengths ("clcl"). The bit lengths of codes to represent tree_cl (these are written as is in the file, it would be crazy to compress these using yet another huffman tree that needs to be represented by yet another set of code lengths)*/ uivector bitlen_cl; size_t datasize = dataend - datapos; /* Due to the huffman compression of huffman tree representations ("two levels"), there are some anologies: bitlen_lld is to tree_cl what data is to tree_ll and tree_d. bitlen_lld_e is to bitlen_lld what lz77_encoded is to data. bitlen_cl is to bitlen_lld_e what bitlen_lld is to lz77_encoded. */ unsigned BFINAL = final; size_t numcodes_ll, numcodes_d, i; unsigned HLIT, HDIST, HCLEN; uivector_init(&lz77_encoded); HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); HuffmanTree_init(&tree_cl); uivector_init(&frequencies_ll); uivector_init(&frequencies_d); uivector_init(&frequencies_cl); uivector_init(&bitlen_lld); uivector_init(&bitlen_lld_e); uivector_init(&bitlen_cl); /*This while loop never loops due to a break at the end, it is here to allow breaking out of it to the cleanup phase on error conditions.*/ while (!error) { if (settings->use_lz77) { error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if (error) break; } else { if (!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); for (i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ } if (!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83 /*alloc fail*/); if (!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); /*Count the frequencies of lit, len and dist codes*/ for (i = 0; i != lz77_encoded.size; ++i) { unsigned symbol = lz77_encoded.data[i]; ++frequencies_ll.data[symbol]; if (symbol > 256) { unsigned dist = lz77_encoded.data[i + 2]; ++frequencies_d.data[dist]; i += 3; } } frequencies_ll.data[256] = 1; /*there will be exactly 1 end code, at the end of the block*/ /*Make both huffman trees, one for the lit and len codes, one for the dist codes*/ error = HuffmanTree_makeFromFrequencies(&tree_ll, frequencies_ll.data, 257, frequencies_ll.size, 15); if (error) break; /*2, not 1, is chosen for mincodes: some buggy PNG decoders require at least 2 symbols in the dist tree*/ error = HuffmanTree_makeFromFrequencies(&tree_d, frequencies_d.data, 2, frequencies_d.size, 15); if (error) break; numcodes_ll = tree_ll.numcodes; if (numcodes_ll > 286) numcodes_ll = 286; numcodes_d = tree_d.numcodes; if (numcodes_d > 30) numcodes_d = 30; /*store the code lengths of both generated trees in bitlen_lld*/ for (i = 0; i != numcodes_ll; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_ll, (unsigned)i)); for (i = 0; i != numcodes_d; ++i) uivector_push_back(&bitlen_lld, HuffmanTree_getLength(&tree_d, (unsigned)i)); /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), 17 (3-10 zeroes), 18 (11-138 zeroes)*/ for (i = 0; i != (unsigned)bitlen_lld.size; ++i) { unsigned j = 0; /*amount of repititions*/ while (i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; if (bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ { ++j; /*include the first zero*/ if (j <= 10) /*repeat code 17 supports max 10 zeroes*/ { uivector_push_back(&bitlen_lld_e, 17); uivector_push_back(&bitlen_lld_e, j - 3); } else /*repeat code 18 supports max 138 zeroes*/ { if (j > 138) j = 138; uivector_push_back(&bitlen_lld_e, 18); uivector_push_back(&bitlen_lld_e, j - 11); } i += (j - 1); } else if (j >= 3) /*repeat code for value other than zero*/ { size_t k; unsigned num = j / 6, rest = j % 6; uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); for (k = 0; k < num; ++k) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, 6 - 3); } if (rest >= 3) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, rest - 3); } else j -= rest; i += j; } else /*too short to benefit from repeat code*/ { uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); } } /*generate tree_cl, the huffmantree of huffmantrees*/ if (!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); for (i = 0; i != bitlen_lld_e.size; ++i) { ++frequencies_cl.data[bitlen_lld_e.data[i]]; /*after a repeat code come the bits that specify the number of repetitions, those don't need to be in the frequencies_cl calculation*/ if (bitlen_lld_e.data[i] >= 16) ++i; } error = HuffmanTree_makeFromFrequencies(&tree_cl, frequencies_cl.data, frequencies_cl.size, frequencies_cl.size, 7); if (error) break; if (!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); for (i = 0; i != tree_cl.numcodes; ++i) { /*lenghts of code length tree is in the order as specified by deflate*/ bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); } while (bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) { /*remove zeros at the end, but minimum size must be 4*/ if (!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); } if (error) break; /* Write everything into the output After the BFINAL and BTYPE, the dynamic block consists out of the following: - 5 bits HLIT, 5 bits HDIST, 4 bits HCLEN - (HCLEN+4)*3 bits code lengths of code length alphabet - HLIT + 257 code lenghts of lit/length alphabet (encoded using the code length alphabet, + possible repetition codes 16, 17, 18) - HDIST + 1 code lengths of distance alphabet (encoded using the code length alphabet, + possible repetition codes 16, 17, 18) - compressed data - 256 (end code) */ /*Write block type*/ addBitToStream(bp, out, BFINAL); addBitToStream(bp, out, 0); /*first bit of BTYPE "dynamic"*/ addBitToStream(bp, out, 1); /*second bit of BTYPE "dynamic"*/ /*write the HLIT, HDIST and HCLEN values*/ HLIT = (unsigned)(numcodes_ll - 257); HDIST = (unsigned)(numcodes_d - 1); HCLEN = (unsigned)bitlen_cl.size - 4; /*trim zeroes for HCLEN. HLIT and HDIST were already trimmed at tree creation*/ while (!bitlen_cl.data[HCLEN + 4 - 1] && HCLEN > 0) --HCLEN; addBitsToStream(bp, out, HLIT, 5); addBitsToStream(bp, out, HDIST, 5); addBitsToStream(bp, out, HCLEN, 4); /*write the code lenghts of the code length alphabet*/ for (i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); /*write the lenghts of the lit/len AND the dist alphabet*/ for (i = 0; i != bitlen_lld_e.size; ++i) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); /*extra bits of repeat codes*/ if (bitlen_lld_e.data[i] == 16) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 2); else if (bitlen_lld_e.data[i] == 17) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 3); else if (bitlen_lld_e.data[i] == 18) addBitsToStream(bp, out, bitlen_lld_e.data[++i], 7); } /*write the compressed data symbols*/ writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); /*error: the length of the end code 256 must be larger than 0*/ if (HuffmanTree_getLength(&tree_ll, 256) == 0) ERROR_BREAK(64); /*write the end code*/ addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); break; /*end of error-while*/ } /*cleanup*/ uivector_cleanup(&lz77_encoded); HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); HuffmanTree_cleanup(&tree_cl); uivector_cleanup(&frequencies_ll); uivector_cleanup(&frequencies_d); uivector_cleanup(&frequencies_cl); uivector_cleanup(&bitlen_lld_e); uivector_cleanup(&bitlen_lld); uivector_cleanup(&bitlen_cl); return error; } static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, const LodePNGCompressSettings* settings, unsigned final) { HuffmanTree tree_ll; /*tree for literal values and length codes*/ HuffmanTree tree_d; /*tree for distance codes*/ unsigned BFINAL = final; unsigned error = 0; size_t i; HuffmanTree_init(&tree_ll); HuffmanTree_init(&tree_d); generateFixedLitLenTree(&tree_ll); generateFixedDistanceTree(&tree_d); addBitToStream(bp, out, BFINAL); addBitToStream(bp, out, 1); /*first bit of BTYPE*/ addBitToStream(bp, out, 0); /*second bit of BTYPE*/ if (settings->use_lz77) /*LZ77 encoded*/ { uivector lz77_encoded; uivector_init(&lz77_encoded); error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if (!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); uivector_cleanup(&lz77_encoded); } else /*no LZ77, but still will be Huffman compressed*/ { for (i = datapos; i < dataend; ++i) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); } } /*add END code*/ if (!error) addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, 256), HuffmanTree_getLength(&tree_ll, 256)); /*cleanup*/ HuffmanTree_cleanup(&tree_ll); HuffmanTree_cleanup(&tree_d); return error; } static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { unsigned error = 0; size_t i, blocksize, numdeflateblocks; size_t bp = 0; /*the bit pointer*/ Hash hash; if (settings->btype > 2) return 61; else if (settings->btype == 0) return deflateNoCompression(out, in, insize); else if (settings->btype == 1) blocksize = insize; else /*if(settings->btype == 2)*/ { /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ blocksize = insize / 8 + 8; if (blocksize < 65536) blocksize = 65536; if (blocksize > 262144) blocksize = 262144; } numdeflateblocks = (insize + blocksize - 1) / blocksize; if (numdeflateblocks == 0) numdeflateblocks = 1; error = hash_init(&hash, settings->windowsize); if (error) return error; for (i = 0; i != numdeflateblocks && !error; ++i) { unsigned final = (i == numdeflateblocks - 1); size_t start = i * blocksize; size_t end = start + blocksize; if (end > insize) end = insize; if (settings->btype == 1) error = deflateFixed(out, &bp, &hash, in, start, end, settings, final); else if (settings->btype == 2) error = deflateDynamic(out, &bp, &hash, in, start, end, settings, final); } hash_cleanup(&hash); return error; } unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); error = lodepng_deflatev(&v, in, insize, settings); *out = v.data; *outsize = v.size; return error; } static unsigned deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if (settings->custom_deflate) { return settings->custom_deflate(out, outsize, in, insize, settings); } else { return lodepng_deflate(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* / Adler32 */ /* ////////////////////////////////////////////////////////////////////////// */ static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { unsigned s1 = adler & 0xffff; unsigned s2 = (adler >> 16) & 0xffff; while (len > 0) { /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ unsigned amount = len > 5552 ? 5552 : len; len -= amount; while (amount > 0) { s1 += (*data++); s2 += s1; --amount; } s1 %= 65521; s2 %= 65521; } return (s2 << 16) | s1; } /*Return the adler32 of the bytes data[0..len-1]*/ static unsigned adler32(const unsigned char* data, unsigned len) { return update_adler32(1L, data, len); } /* ////////////////////////////////////////////////////////////////////////// */ /* / Zlib / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_DECODER unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { unsigned error = 0; unsigned CM, CINFO, FDICT; if (insize < 2) return 53; /*error, size of zlib data too small*/ /*read information from zlib header*/ if ((in[0] * 256 + in[1]) % 31 != 0) { /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ return 24; } CM = in[0] & 15; CINFO = (in[0] >> 4) & 15; /*FCHECK = in[1] & 31;*/ /*FCHECK is already tested above*/ FDICT = (in[1] >> 5) & 1; /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ if (CM != 8 || CINFO > 7) { /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ return 25; } if (FDICT != 0) { /*error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary."*/ return 26; } error = inflate(out, outsize, in + 2, insize - 2, settings); if (error) return error; if (!settings->ignore_adler32) { unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); unsigned checksum = adler32(*out, (unsigned)(*outsize)); if (checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ } return 0; /*no error*/ } static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if (settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); } else { return lodepng_zlib_decompress(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { /*initially, *out must be NULL and outsize 0, if you just give some random *out that's pointing to a non allocated buffer, this'll crash*/ ucvector outv; size_t i; unsigned error; unsigned char* deflatedata = 0; size_t deflatesize = 0; /*zlib data: 1 byte CMF (CM+CINFO), 1 byte FLG, deflate data, 4 byte ADLER32 checksum of the Decompressed data*/ unsigned CMF = 120; /*0b01111000: CM 8, CINFO 7. With CINFO 7, any window size up to 32768 can be used.*/ unsigned FLEVEL = 0; unsigned FDICT = 0; unsigned CMFFLG = 256 * CMF + FDICT * 32 + FLEVEL * 64; unsigned FCHECK = 31 - CMFFLG % 31; CMFFLG += FCHECK; /*ucvector-controlled version of the output buffer, for dynamic array*/ ucvector_init_buffer(&outv, *out, *outsize); ucvector_push_back(&outv, (unsigned char)(CMFFLG >> 8)); ucvector_push_back(&outv, (unsigned char)(CMFFLG & 255)); error = deflate(&deflatedata, &deflatesize, in, insize, settings); if (!error) { unsigned ADLER32 = adler32(in, (unsigned)insize); for (i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); lodepng_free(deflatedata); lodepng_add32bitInt(&outv, ADLER32); } *out = outv.data; *outsize = outv.size; return error; } /* compress using the default or custom zlib function */ static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if (settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); } else { return lodepng_zlib_compress(out, outsize, in, insize, settings); } } #endif /*LODEPNG_COMPILE_ENCODER*/ #else /*no LODEPNG_COMPILE_ZLIB*/ #ifdef LODEPNG_COMPILE_DECODER static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGDecompressSettings* settings) { if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, const LodePNGCompressSettings* settings) { if (!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_ZLIB*/ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_ENCODER /*this is a good tradeoff between speed and compression ratio*/ #define DEFAULT_WINDOWSIZE 2048 void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ settings->btype = 2; settings->use_lz77 = 1; settings->windowsize = DEFAULT_WINDOWSIZE; settings->minmatch = 3; settings->nicematch = 128; settings->lazymatching = 1; settings->custom_zlib = 0; settings->custom_deflate = 0; settings->custom_context = 0; } const LodePNGCompressSettings lodepng_default_compress_settings = { 2, 1, DEFAULT_WINDOWSIZE, 3, 128, 1, 0, 0, 0 }; #endif /*LODEPNG_COMPILE_ENCODER*/ #ifdef LODEPNG_COMPILE_DECODER void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { settings->ignore_adler32 = 0; settings->custom_zlib = 0; settings->custom_inflate = 0; settings->custom_context = 0; } const LodePNGDecompressSettings lodepng_default_decompress_settings = { 0, 0, 0, 0 }; #endif /*LODEPNG_COMPILE_DECODER*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // End of Zlib related code. Begin of PNG related code. // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_PNG /* ////////////////////////////////////////////////////////////////////////// */ /* / CRC32 / */ /* ////////////////////////////////////////////////////////////////////////// */ #ifndef LODEPNG_NO_COMPILE_CRC /* CRC polynomial: 0xedb88320 */ static unsigned lodepng_crc32_table[256] = { 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u }; /*Return the CRC of the bytes buf[0..len-1].*/ unsigned lodepng_crc32(const unsigned char* data, size_t length) { unsigned r = 0xffffffffu; size_t i; for (i = 0; i < length; ++i) { r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8); } return r ^ 0xffffffffu; } #else /* !LODEPNG_NO_COMPILE_CRC */ unsigned lodepng_crc32(const unsigned char* data, size_t length); #endif /* !LODEPNG_NO_COMPILE_CRC */ /* ////////////////////////////////////////////////////////////////////////// */ /* / Reading and writing single bits and bytes from/to stream for LodePNG / */ /* ////////////////////////////////////////////////////////////////////////// */ static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); ++(*bitpointer); return result; } static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0; size_t i; for (i = 0; i < nbits; ++i) { result <<= 1; result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); } return result; } #ifdef LODEPNG_COMPILE_DECODER static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream must be 0 for this to work*/ if (bit) { /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); } ++(*bitpointer); } #endif /*LODEPNG_COMPILE_DECODER*/ static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream may be 0 or 1 for this to work*/ if (bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); ++(*bitpointer); } /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG chunks / */ /* ////////////////////////////////////////////////////////////////////////// */ unsigned lodepng_chunk_length(const unsigned char* chunk) { return lodepng_read32bitInt(&chunk[0]); } void lodepng_chunk_type(char type[5], const unsigned char* chunk) { unsigned i; for (i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; type[4] = 0; /*null termination char*/ } unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) { if (strlen(type) != 4) return 0; return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); } unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) { return((chunk[4] & 32) != 0); } unsigned char lodepng_chunk_private(const unsigned char* chunk) { return((chunk[6] & 32) != 0); } unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) { return((chunk[7] & 32) != 0); } unsigned char* lodepng_chunk_data(unsigned char* chunk) { return &chunk[8]; } const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) { return &chunk[8]; } unsigned lodepng_chunk_check_crc(const unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ unsigned checksum = lodepng_crc32(&chunk[4], length + 4); if (CRC != checksum) return 1; else return 0; } void lodepng_chunk_generate_crc(unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_crc32(&chunk[4], length + 4); lodepng_set32bitInt(chunk + 8 + length, CRC); } unsigned char* lodepng_chunk_next(unsigned char* chunk) { unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; return chunk + total_chunk_length; } const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) { unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; return chunk + total_chunk_length; } unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) { unsigned i; unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; unsigned char *chunk_start, *new_buffer; size_t new_length = (*outlength) + total_chunk_length; if (new_length < total_chunk_length || new_length < (*outlength)) return 77; /*integer overflow happened*/ new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); if (!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outlength) = new_length; chunk_start = &(*out)[new_length - total_chunk_length]; for (i = 0; i != total_chunk_length; ++i) chunk_start[i] = chunk[i]; return 0; } unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, const char* type, const unsigned char* data) { unsigned i; unsigned char *chunk, *new_buffer; size_t new_length = (*outlength) + length + 12; if (new_length < length + 12 || new_length < (*outlength)) return 77; /*integer overflow happened*/ new_buffer = (unsigned char*)lodepng_realloc(*out, new_length); if (!new_buffer) return 83; /*alloc fail*/ (*out) = new_buffer; (*outlength) = new_length; chunk = &(*out)[(*outlength) - length - 12]; /*1: length*/ lodepng_set32bitInt(chunk, (unsigned)length); /*2: chunk name (4 letters)*/ chunk[4] = (unsigned char)type[0]; chunk[5] = (unsigned char)type[1]; chunk[6] = (unsigned char)type[2]; chunk[7] = (unsigned char)type[3]; /*3: the data*/ for (i = 0; i != length; ++i) chunk[8 + i] = data[i]; /*4: CRC (of the chunkname characters and the data)*/ lodepng_chunk_generate_crc(chunk); return 0; } /* ////////////////////////////////////////////////////////////////////////// */ /* / Color types and such / */ /* ////////////////////////////////////////////////////////////////////////// */ /*return type is a LodePNG error code*/ static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ { switch (colortype) { case 0: if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ case 2: if (!(bd == 8 || bd == 16)) return 37; break; /*RGB*/ case 3: if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37; break; /*palette*/ case 4: if (!(bd == 8 || bd == 16)) return 37; break; /*grey + alpha*/ case 6: if (!(bd == 8 || bd == 16)) return 37; break; /*RGBA*/ default: return 31; } return 0; /*allowed color type / bits combination*/ } static unsigned getNumColorChannels(LodePNGColorType colortype) { switch (colortype) { case 0: return 1; /*grey*/ case 2: return 3; /*RGB*/ case 3: return 1; /*palette*/ case 4: return 2; /*grey + alpha*/ case 6: return 4; /*RGBA*/ } return 0; /*unexisting color type*/ } static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { /*bits per pixel is amount of channels * bits per channel*/ return getNumColorChannels(colortype) * bitdepth; } /* ////////////////////////////////////////////////////////////////////////// */ void lodepng_color_mode_init(LodePNGColorMode* info) { info->key_defined = 0; info->key_r = info->key_g = info->key_b = 0; info->colortype = LCT_RGBA; info->bitdepth = 8; info->palette = 0; info->palettesize = 0; } void lodepng_color_mode_cleanup(LodePNGColorMode* info) { lodepng_palette_clear(info); } unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { size_t i; lodepng_color_mode_cleanup(dest); *dest = *source; if (source->palette) { dest->palette = (unsigned char*)lodepng_malloc(1024); if (!dest->palette && source->palettesize) return 83; /*alloc fail*/ for (i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; } return 0; } static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { size_t i; if (a->colortype != b->colortype) return 0; if (a->bitdepth != b->bitdepth) return 0; if (a->key_defined != b->key_defined) return 0; if (a->key_defined) { if (a->key_r != b->key_r) return 0; if (a->key_g != b->key_g) return 0; if (a->key_b != b->key_b) return 0; } if (a->palettesize != b->palettesize) return 0; for (i = 0; i != a->palettesize * 4; ++i) { if (a->palette[i] != b->palette[i]) return 0; } return 1; } #ifdef LODEPNG_COMPILE_ENCODER #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /* Makes a temporary LodePNGColorMode that does not need cleanup (no palette) */ static LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) { LodePNGColorMode result; lodepng_color_mode_init(&result); result.colortype = colortype; result.bitdepth = bitdepth; return result; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ #endif /*LODEPNG_COMPILE_ENCODER*/ void lodepng_palette_clear(LodePNGColorMode* info) { if (info->palette) lodepng_free(info->palette); info->palette = 0; info->palettesize = 0; } unsigned lodepng_palette_add(LodePNGColorMode* info, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { unsigned char* data; /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with the max of 256 colors, it'll have the exact alloc size*/ if (!info->palette) /*allocate palette if empty*/ { /*room for 256 colors with 4 bytes each*/ data = (unsigned char*)lodepng_realloc(info->palette, 1024); if (!data) return 83; /*alloc fail*/ else info->palette = data; } info->palette[4 * info->palettesize + 0] = r; info->palette[4 * info->palettesize + 1] = g; info->palette[4 * info->palettesize + 2] = b; info->palette[4 * info->palettesize + 3] = a; ++info->palettesize; return 0; } /*calculate bits per pixel out of colortype and bitdepth*/ unsigned lodepng_get_bpp(const LodePNGColorMode* info) { return lodepng_get_bpp_lct(info->colortype, info->bitdepth); } unsigned lodepng_get_channels(const LodePNGColorMode* info) { return getNumColorChannels(info->colortype); } unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; } unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { return (info->colortype & 4) != 0; /*4 or 6*/ } unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { return info->colortype == LCT_PALETTE; } unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { size_t i; for (i = 0; i != info->palettesize; ++i) { if (info->palette[i * 4 + 3] < 255) return 1; } return 0; } unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { return info->key_defined || lodepng_is_alpha_type(info) || lodepng_has_palette_alpha(info); } size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); size_t n = (size_t)w * (size_t)h; return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; } size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); } #ifdef LODEPNG_COMPILE_PNG #ifdef LODEPNG_COMPILE_DECODER /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, and in addition has one extra byte per line: the filter byte. So this gives a larger result than lodepng_get_raw_size. */ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) { size_t bpp = lodepng_get_bpp(color); /* + 1 for the filter byte, and possibly plus padding bits per line */ size_t line = ((size_t)(w / 8) * bpp) + 1 + ((w & 7) * bpp + 7) / 8; return (size_t)h * line; } /* Safely check if multiplying two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ static int lodepng_mulofl(size_t a, size_t b, size_t* result) { *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ return (a != 0 && *result / a != b); } /* Safely check if adding two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ static int lodepng_addofl(size_t a, size_t b, size_t* result) { *result = a + b; /* Unsigned addition is well defined and safe in C90 */ return *result < a; } /*Safely checks whether size_t overflow can be caused due to amount of pixels. This check is overcautious rather than precise. If this check indicates no overflow, you can safely compute in a size_t (but not an unsigned): -(size_t)w * (size_t)h * 8 -amount of bytes in IDAT (including filter, padding and Adam7 bytes) -amount of bytes in raw color model Returns 1 if overflow possible, 0 if not. */ static int lodepng_pixel_overflow(unsigned w, unsigned h, const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) { size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); size_t numpixels, total; size_t line; /* bytes per line in worst case */ if (lodepng_mulofl((size_t)w, (size_t)h, &numpixels)) return 1; if (lodepng_mulofl(numpixels, 8, &total)) return 1; /* bit pointer with 8-bit color, or 8 bytes per channel color */ /* Bytes per scanline with the expression "(w / 8) * bpp) + ((w & 7) * bpp + 7) / 8" */ if (lodepng_mulofl((size_t)(w / 8), bpp, &line)) return 1; if (lodepng_addofl(line, ((w & 7) * bpp + 7) / 8, &line)) return 1; if (lodepng_addofl(line, 5, &line)) return 1; /* 5 bytes overhead per line: 1 filterbyte, 4 for Adam7 worst case */ if (lodepng_mulofl(line, h, &total)) return 1; /* Total bytes in worst case */ return 0; /* no overflow */ } #endif /*LODEPNG_COMPILE_DECODER*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static void LodePNGUnknownChunks_init(LodePNGInfo* info) { unsigned i; for (i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; for (i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; } static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { unsigned i; for (i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); } static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { unsigned i; LodePNGUnknownChunks_cleanup(dest); for (i = 0; i != 3; ++i) { size_t j; dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); if (!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ for (j = 0; j < src->unknown_chunks_size[i]; ++j) { dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; } } return 0; } /******************************************************************************/ static void LodePNGText_init(LodePNGInfo* info) { info->text_num = 0; info->text_keys = NULL; info->text_strings = NULL; } static void LodePNGText_cleanup(LodePNGInfo* info) { size_t i; for (i = 0; i != info->text_num; ++i) { string_cleanup(&info->text_keys[i]); string_cleanup(&info->text_strings[i]); } lodepng_free(info->text_keys); lodepng_free(info->text_strings); } static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->text_keys = 0; dest->text_strings = 0; dest->text_num = 0; for (i = 0; i != source->text_num; ++i) { CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); } return 0; } void lodepng_clear_text(LodePNGInfo* info) { LodePNGText_cleanup(info); } unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); if (!new_keys || !new_strings) { lodepng_free(new_keys); lodepng_free(new_strings); return 83; /*alloc fail*/ } ++info->text_num; info->text_keys = new_keys; info->text_strings = new_strings; info->text_keys[info->text_num - 1] = alloc_string(key); info->text_strings[info->text_num - 1] = alloc_string(str); return 0; } /******************************************************************************/ static void LodePNGIText_init(LodePNGInfo* info) { info->itext_num = 0; info->itext_keys = NULL; info->itext_langtags = NULL; info->itext_transkeys = NULL; info->itext_strings = NULL; } static void LodePNGIText_cleanup(LodePNGInfo* info) { size_t i; for (i = 0; i != info->itext_num; ++i) { string_cleanup(&info->itext_keys[i]); string_cleanup(&info->itext_langtags[i]); string_cleanup(&info->itext_transkeys[i]); string_cleanup(&info->itext_strings[i]); } lodepng_free(info->itext_keys); lodepng_free(info->itext_langtags); lodepng_free(info->itext_transkeys); lodepng_free(info->itext_strings); } static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->itext_keys = 0; dest->itext_langtags = 0; dest->itext_transkeys = 0; dest->itext_strings = 0; dest->itext_num = 0; for (i = 0; i != source->itext_num; ++i) { CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], source->itext_transkeys[i], source->itext_strings[i])); } return 0; } void lodepng_clear_itext(LodePNGInfo* info) { LodePNGIText_cleanup(info); } unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, const char* transkey, const char* str) { char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); if (!new_keys || !new_langtags || !new_transkeys || !new_strings) { lodepng_free(new_keys); lodepng_free(new_langtags); lodepng_free(new_transkeys); lodepng_free(new_strings); return 83; /*alloc fail*/ } ++info->itext_num; info->itext_keys = new_keys; info->itext_langtags = new_langtags; info->itext_transkeys = new_transkeys; info->itext_strings = new_strings; info->itext_keys[info->itext_num - 1] = alloc_string(key); info->itext_langtags[info->itext_num - 1] = alloc_string(langtag); info->itext_transkeys[info->itext_num - 1] = alloc_string(transkey); info->itext_strings[info->itext_num - 1] = alloc_string(str); return 0; } /* same as set but does not delete */ static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { info->iccp_name = alloc_string(name); info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size); if (!info->iccp_name || !info->iccp_profile) return 83; /*alloc fail*/ memcpy(info->iccp_profile, profile, profile_size); info->iccp_profile_size = profile_size; return 0; /*ok*/ } unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { if (info->iccp_name) lodepng_clear_icc(info); return lodepng_assign_icc(info, name, profile, profile_size); } void lodepng_clear_icc(LodePNGInfo* info) { string_cleanup(&info->iccp_name); lodepng_free(info->iccp_profile); info->iccp_profile = NULL; info->iccp_profile_size = 0; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ void lodepng_info_init(LodePNGInfo* info) { lodepng_color_mode_init(&info->color); info->interlace_method = 0; info->compression_method = 0; info->filter_method = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS info->background_defined = 0; info->background_r = info->background_g = info->background_b = 0; LodePNGText_init(info); LodePNGIText_init(info); info->time_defined = 0; info->phys_defined = 0; info->gama_defined = 0; info->chrm_defined = 0; info->srgb_defined = 0; info->iccp_defined = 0; info->iccp_name = NULL; info->iccp_profile = NULL; LodePNGUnknownChunks_init(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } void lodepng_info_cleanup(LodePNGInfo* info) { lodepng_color_mode_cleanup(&info->color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS LodePNGText_cleanup(info); LodePNGIText_cleanup(info); lodepng_clear_icc(info); LodePNGUnknownChunks_cleanup(info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { lodepng_info_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->color); CERROR_TRY_RETURN(lodepng_color_mode_copy(&dest->color, &source->color)); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); if (source->iccp_defined) { CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size)); } LodePNGUnknownChunks_init(dest); CERROR_TRY_RETURN(LodePNGUnknownChunks_copy(dest, source)); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ return 0; } /* ////////////////////////////////////////////////////////////////////////// */ /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) { unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ unsigned p = index & m; in &= (1u << bits) - 1u; /*filter out any other bits of the input value*/ in = in << (bits * (m - p)); if (p == 0) out[index * bits / 8] = in; else out[index * bits / 8] |= in; } typedef struct ColorTree ColorTree; /* One node of a color tree This is the data structure used to count the number of unique colors and to get a palette index for a color. It's like an octree, but because the alpha channel is used too, each node has 16 instead of 8 children. */ struct ColorTree { ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ int index; /*the payload. Only has a meaningful value if this is in the last level*/ }; static void color_tree_init(ColorTree* tree) { int i; for (i = 0; i != 16; ++i) tree->children[i] = 0; tree->index = -1; } static void color_tree_cleanup(ColorTree* tree) { int i; for (i = 0; i != 16; ++i) { if (tree->children[i]) { color_tree_cleanup(tree->children[i]); lodepng_free(tree->children[i]); } } } /*returns -1 if color not present, its index otherwise*/ static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { int bit = 0; for (bit = 0; bit < 8; ++bit) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); if (!tree->children[i]) return -1; else tree = tree->children[i]; } return tree ? tree->index : -1; } #ifdef LODEPNG_COMPILE_ENCODER static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { return color_tree_get(tree, r, g, b, a) >= 0; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*color is not allowed to already exist. Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ static void color_tree_add(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) { int bit; for (bit = 0; bit < 8; ++bit) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); if (!tree->children[i]) { tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); color_tree_init(tree->children[i]); } tree = tree->children[i]; } tree->index = (int)index; } /*put a pixel, given its RGBA color, into image of any color type*/ static unsigned rgba8ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { if (mode->colortype == LCT_GREY) { unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; if (mode->bitdepth == 8) out[i] = grey; else if (mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; else { /*take the most significant bits of grey*/ grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); addColorBits(out, i, mode->bitdepth, grey); } } else if (mode->colortype == LCT_RGB) { if (mode->bitdepth == 8) { out[i * 3 + 0] = r; out[i * 3 + 1] = g; out[i * 3 + 2] = b; } else { out[i * 6 + 0] = out[i * 6 + 1] = r; out[i * 6 + 2] = out[i * 6 + 3] = g; out[i * 6 + 4] = out[i * 6 + 5] = b; } } else if (mode->colortype == LCT_PALETTE) { int index = color_tree_get(tree, r, g, b, a); if (index < 0) return 82; /*color not in palette*/ if (mode->bitdepth == 8) out[i] = index; else addColorBits(out, i, mode->bitdepth, (unsigned)index); } else if (mode->colortype == LCT_GREY_ALPHA) { unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; if (mode->bitdepth == 8) { out[i * 2 + 0] = grey; out[i * 2 + 1] = a; } else if (mode->bitdepth == 16) { out[i * 4 + 0] = out[i * 4 + 1] = grey; out[i * 4 + 2] = out[i * 4 + 3] = a; } } else if (mode->colortype == LCT_RGBA) { if (mode->bitdepth == 8) { out[i * 4 + 0] = r; out[i * 4 + 1] = g; out[i * 4 + 2] = b; out[i * 4 + 3] = a; } else { out[i * 8 + 0] = out[i * 8 + 1] = r; out[i * 8 + 2] = out[i * 8 + 3] = g; out[i * 8 + 4] = out[i * 8 + 5] = b; out[i * 8 + 6] = out[i * 8 + 7] = a; } } return 0; /*no error*/ } /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ static void rgba16ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, unsigned short r, unsigned short g, unsigned short b, unsigned short a) { if (mode->colortype == LCT_GREY) { unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; out[i * 2 + 0] = (grey >> 8) & 255; out[i * 2 + 1] = grey & 255; } else if (mode->colortype == LCT_RGB) { out[i * 6 + 0] = (r >> 8) & 255; out[i * 6 + 1] = r & 255; out[i * 6 + 2] = (g >> 8) & 255; out[i * 6 + 3] = g & 255; out[i * 6 + 4] = (b >> 8) & 255; out[i * 6 + 5] = b & 255; } else if (mode->colortype == LCT_GREY_ALPHA) { unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; out[i * 4 + 0] = (grey >> 8) & 255; out[i * 4 + 1] = grey & 255; out[i * 4 + 2] = (a >> 8) & 255; out[i * 4 + 3] = a & 255; } else if (mode->colortype == LCT_RGBA) { out[i * 8 + 0] = (r >> 8) & 255; out[i * 8 + 1] = r & 255; out[i * 8 + 2] = (g >> 8) & 255; out[i * 8 + 3] = g & 255; out[i * 8 + 4] = (b >> 8) & 255; out[i * 8 + 5] = b & 255; out[i * 8 + 6] = (a >> 8) & 255; out[i * 8 + 7] = a & 255; } } /*Get RGBA8 color of pixel with index i (y * width + x) from the raw image with given color type.*/ static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode) { if (mode->colortype == LCT_GREY) { if (mode->bitdepth == 8) { *r = *g = *b = in[i]; if (mode->key_defined && *r == mode->key_r) *a = 0; else *a = 255; } else if (mode->bitdepth == 16) { *r = *g = *b = in[i * 2 + 0]; if (mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 255; } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = i * mode->bitdepth; unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); *r = *g = *b = (value * 255) / highest; if (mode->key_defined && value == mode->key_r) *a = 0; else *a = 255; } } else if (mode->colortype == LCT_RGB) { if (mode->bitdepth == 8) { *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; if (mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; else *a = 255; } else { *r = in[i * 6 + 0]; *g = in[i * 6 + 2]; *b = in[i * 6 + 4]; if (mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 255; } } else if (mode->colortype == LCT_PALETTE) { unsigned index; if (mode->bitdepth == 8) index = in[i]; else { size_t j = i * mode->bitdepth; index = readBitsFromReversedStream(&j, in, mode->bitdepth); } if (index >= mode->palettesize) { /*This is an error according to the PNG spec, but common PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ *r = *g = *b = 0; *a = 255; } else { *r = mode->palette[index * 4 + 0]; *g = mode->palette[index * 4 + 1]; *b = mode->palette[index * 4 + 2]; *a = mode->palette[index * 4 + 3]; } } else if (mode->colortype == LCT_GREY_ALPHA) { if (mode->bitdepth == 8) { *r = *g = *b = in[i * 2 + 0]; *a = in[i * 2 + 1]; } else { *r = *g = *b = in[i * 4 + 0]; *a = in[i * 4 + 2]; } } else if (mode->colortype == LCT_RGBA) { if (mode->bitdepth == 8) { *r = in[i * 4 + 0]; *g = in[i * 4 + 1]; *b = in[i * 4 + 2]; *a = in[i * 4 + 3]; } else { *r = in[i * 8 + 0]; *g = in[i * 8 + 2]; *b = in[i * 8 + 4]; *a = in[i * 8 + 6]; } } } /*Similar to getPixelColorRGBA8, but with all the for loops inside of the color mode test cases, optimized to convert the colors much faster, when converting to RGBA or RGB with 8 bit per cannel. buffer must be RGBA or RGB output with enough memory, if has_alpha is true the output is RGBA. mode has the color mode of the input buffer.*/ static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, unsigned has_alpha, const unsigned char* in, const LodePNGColorMode* mode) { unsigned num_channels = has_alpha ? 4 : 3; size_t i; if (mode->colortype == LCT_GREY) { if (mode->bitdepth == 8) { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i]; if (has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; } } else if (mode->bitdepth == 16) { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2]; if (has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; } } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = 0; for (i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; if (has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; } } } else if (mode->colortype == LCT_RGB) { if (mode->bitdepth == 8) { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 3 + 0]; buffer[1] = in[i * 3 + 1]; buffer[2] = in[i * 3 + 2]; if (has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r && buffer[1] == mode->key_g && buffer[2] == mode->key_b ? 0 : 255; } } else { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 6 + 0]; buffer[1] = in[i * 6 + 2]; buffer[2] = in[i * 6 + 4]; if (has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256U * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; } } } else if (mode->colortype == LCT_PALETTE) { unsigned index; size_t j = 0; for (i = 0; i != numpixels; ++i, buffer += num_channels) { if (mode->bitdepth == 8) index = in[i]; else index = readBitsFromReversedStream(&j, in, mode->bitdepth); if (index >= mode->palettesize) { /*This is an error according to the PNG spec, but most PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ buffer[0] = buffer[1] = buffer[2] = 0; if (has_alpha) buffer[3] = 255; } else { buffer[0] = mode->palette[index * 4 + 0]; buffer[1] = mode->palette[index * 4 + 1]; buffer[2] = mode->palette[index * 4 + 2]; if (has_alpha) buffer[3] = mode->palette[index * 4 + 3]; } } } else if (mode->colortype == LCT_GREY_ALPHA) { if (mode->bitdepth == 8) { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; if (has_alpha) buffer[3] = in[i * 2 + 1]; } } else { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; if (has_alpha) buffer[3] = in[i * 4 + 2]; } } } else if (mode->colortype == LCT_RGBA) { if (mode->bitdepth == 8) { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 4 + 0]; buffer[1] = in[i * 4 + 1]; buffer[2] = in[i * 4 + 2]; if (has_alpha) buffer[3] = in[i * 4 + 3]; } } else { for (i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 8 + 0]; buffer[1] = in[i * 8 + 2]; buffer[2] = in[i * 8 + 4]; if (has_alpha) buffer[3] = in[i * 8 + 6]; } } } } /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with given color type, but the given color type must be 16-bit itself.*/ static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, const unsigned char* in, size_t i, const LodePNGColorMode* mode) { if (mode->colortype == LCT_GREY) { *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; if (mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 65535; } else if (mode->colortype == LCT_RGB) { *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; if (mode->key_defined && 256u * in[i * 6 + 0] + in[i * 6 + 1] == mode->key_r && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 65535; } else if (mode->colortype == LCT_GREY_ALPHA) { *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; } else if (mode->colortype == LCT_RGBA) { *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; *a = 256u * in[i * 8 + 6] + in[i * 8 + 7]; } } unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, unsigned w, unsigned h) { size_t i; ColorTree tree; size_t numpixels = (size_t)w * (size_t)h; unsigned error = 0; if (lodepng_color_mode_equal(mode_out, mode_in)) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); for (i = 0; i != numbytes; ++i) out[i] = in[i]; return 0; } if (mode_out->colortype == LCT_PALETTE) { size_t palettesize = mode_out->palettesize; const unsigned char* palette = mode_out->palette; size_t palsize = (size_t)1u << mode_out->bitdepth; /*if the user specified output palette but did not give the values, assume they want the values of the input color type (assuming that one is palette). Note that we never create a new palette ourselves.*/ if (palettesize == 0) { palettesize = mode_in->palettesize; palette = mode_in->palette; /*if the input was also palette with same bitdepth, then the color types are also equal, so copy literally. This to preserve the exact indices that were in the PNG even in case there are duplicate colors in the palette.*/ if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); for (i = 0; i != numbytes; ++i) out[i] = in[i]; return 0; } } if (palettesize < palsize) palsize = palettesize; color_tree_init(&tree); for (i = 0; i != palsize; ++i) { const unsigned char* p = &palette[i * 4]; color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); } } if (mode_in->bitdepth == 16 && mode_out->bitdepth == 16) { for (i = 0; i != numpixels; ++i) { unsigned short r = 0, g = 0, b = 0, a = 0; getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); rgba16ToPixel(out, i, mode_out, r, g, b, a); } } else if (mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) { getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); } else if (mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); } else { unsigned char r = 0, g = 0, b = 0, a = 0; for (i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); if (error) break; } } if (mode_out->colortype == LCT_PALETTE) { color_tree_cleanup(&tree); } return error; } /* Converts a single rgb color without alpha from one type to another, color bits truncated to their bitdepth. In case of single channel (grey or palette), only the r channel is used. Slow function, do not use to process all pixels of an image. Alpha channel not supported on purpose: this is for bKGD, supporting alpha may prevent it from finding a color in the palette, from the specification it looks like bKGD should ignore the alpha values of the palette since it can use any palette index but doesn't have an alpha channel. Idem with ignoring color key. */ unsigned lodepng_convert_rgb( unsigned* r_out, unsigned* g_out, unsigned* b_out, unsigned r_in, unsigned g_in, unsigned b_in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) { unsigned r = 0, g = 0, b = 0; unsigned mul = 65535 / ((1 << mode_in->bitdepth) - 1); /*65535, 21845, 4369, 257, 1*/ unsigned shift = 16 - mode_out->bitdepth; if (mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) { r = g = b = r_in * mul; } else if (mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) { r = r_in * mul; g = g_in * mul; b = b_in * mul; } else if (mode_in->colortype == LCT_PALETTE) { if (r_in >= mode_in->palettesize) return 82; r = mode_in->palette[r_in * 4 + 0] * 257; g = mode_in->palette[r_in * 4 + 1] * 257; b = mode_in->palette[r_in * 4 + 2] * 257; } else { return 31; } /* now convert to output format */ if (mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) { *r_out = r >> shift; } else if (mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) { *r_out = r >> shift; *g_out = g >> shift; *b_out = b >> shift; } else if (mode_out->colortype == LCT_PALETTE) { unsigned i; /* a 16-bit color cannot be in the palette */ if ((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82; for (i = 0; i < mode_out->palettesize; i++) { unsigned j = i * 4; if ((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] && (b >> 8) == mode_out->palette[j + 2]) { *r_out = i; return 0; } } return 82; } else { return 31; } return 0; } #ifdef LODEPNG_COMPILE_ENCODER void lodepng_color_profile_init(LodePNGColorProfile* profile) { profile->colored = 0; profile->key = 0; profile->key_r = profile->key_g = profile->key_b = 0; profile->alpha = 0; profile->numcolors = 0; profile->bits = 1; profile->numpixels = 0; } /*function used for debug purposes with C++*/ /*void printColorProfile(LodePNGColorProfile* p) { std::cout << "colored: " << (int)p->colored << ", "; std::cout << "key: " << (int)p->key << ", "; std::cout << "key_r: " << (int)p->key_r << ", "; std::cout << "key_g: " << (int)p->key_g << ", "; std::cout << "key_b: " << (int)p->key_b << ", "; std::cout << "alpha: " << (int)p->alpha << ", "; std::cout << "numcolors: " << (int)p->numcolors << ", "; std::cout << "bits: " << (int)p->bits << std::endl; }*/ /*Returns how many bits needed to represent given value (max 8 bit)*/ static unsigned getValueRequiredBits(unsigned char value) { if (value == 0 || value == 255) return 1; /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ if (value % 17 == 0) return value % 85 == 0 ? 2 : 4; return 8; } /*profile must already have been inited. It's ok to set some parameters of profile to done already.*/ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* mode_in) { unsigned error = 0; size_t i; ColorTree tree; size_t numpixels = (size_t)w * (size_t)h; /* mark things as done already if it would be impossible to have a more expensive case */ unsigned colored_done = lodepng_is_greyscale_type(mode_in) ? 1 : 0; unsigned alpha_done = lodepng_can_have_alpha(mode_in) ? 0 : 1; unsigned numcolors_done = 0; unsigned bpp = lodepng_get_bpp(mode_in); unsigned bits_done = (profile->bits == 1 && bpp == 1) ? 1 : 0; unsigned sixteen = 0; /* whether the input image is 16 bit */ unsigned maxnumcolors = 257; if (bpp <= 8) maxnumcolors = LODEPNG_MIN(257, profile->numcolors + (1 << bpp)); profile->numpixels += numpixels; color_tree_init(&tree); /*If the profile was already filled in from previous data, fill its palette in tree and mark things as done already if we know they are the most expensive case already*/ if (profile->alpha) alpha_done = 1; if (profile->colored) colored_done = 1; if (profile->bits == 16) numcolors_done = 1; if (profile->bits >= bpp) bits_done = 1; if (profile->numcolors >= maxnumcolors) numcolors_done = 1; if (!numcolors_done) { for (i = 0; i < profile->numcolors; i++) { const unsigned char* color = &profile->palette[i * 4]; color_tree_add(&tree, color[0], color[1], color[2], color[3], i); } } /*Check if the 16-bit input is truly 16-bit*/ if (mode_in->bitdepth == 16 && !sixteen) { unsigned short r, g, b, a; for (i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if ((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ { profile->bits = 16; sixteen = 1; bits_done = 1; numcolors_done = 1; /*counting colors no longer useful, palette doesn't support 16-bit*/ break; } } } if (sixteen) { unsigned short r = 0, g = 0, b = 0, a = 0; for (i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if (!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; } if (!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); if (a != 65535 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; profile->key = 0; alpha_done = 1; } else if (a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; } else if (a == 65535 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; alpha_done = 1; } } if (alpha_done && numcolors_done && colored_done && bits_done) break; } if (profile->key && !profile->alpha) { for (i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if (a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; alpha_done = 1; } } } } else /* < 16-bit */ { unsigned char r = 0, g = 0, b = 0, a = 0; for (i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); if (!bits_done && profile->bits < 8) { /*only r is checked, < 8 bits is only relevant for greyscale*/ unsigned bits = getValueRequiredBits(r); if (bits > profile->bits) profile->bits = bits; } bits_done = (profile->bits >= bpp); if (!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; if (profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ } if (!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); if (a != 255 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; profile->key = 0; alpha_done = 1; if (profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } else if (a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; } else if (a == 255 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; alpha_done = 1; if (profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } } if (!numcolors_done) { if (!color_tree_has(&tree, r, g, b, a)) { color_tree_add(&tree, r, g, b, a, profile->numcolors); if (profile->numcolors < 256) { unsigned char* p = profile->palette; unsigned n = profile->numcolors; p[n * 4 + 0] = r; p[n * 4 + 1] = g; p[n * 4 + 2] = b; p[n * 4 + 3] = a; } ++profile->numcolors; numcolors_done = profile->numcolors >= maxnumcolors; } } if (alpha_done && numcolors_done && colored_done && bits_done) break; } if (profile->key && !profile->alpha) { for (i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); if (a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; alpha_done = 1; if (profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } } } /*make the profile's key always 16-bit for consistency - repeat each byte twice*/ profile->key_r += (profile->key_r << 8); profile->key_g += (profile->key_g << 8); profile->key_b += (profile->key_b << 8); } color_tree_cleanup(&tree); return error; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*Adds a single color to the color profile. The profile must already have been inited. The color must be given as 16-bit (with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for all pixels of an image but only for a few additional values. */ static unsigned lodepng_color_profile_add(LodePNGColorProfile* profile, unsigned r, unsigned g, unsigned b, unsigned a) { unsigned error = 0; unsigned char image[8]; LodePNGColorMode mode; lodepng_color_mode_init(&mode); image[0] = r >> 8; image[1] = r; image[2] = g >> 8; image[3] = g; image[4] = b >> 8; image[5] = b; image[6] = a >> 8; image[7] = a; mode.bitdepth = 16; mode.colortype = LCT_RGBA; error = lodepng_get_color_profile(profile, image, 1, 1, &mode); lodepng_color_mode_cleanup(&mode); return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Autochoose color model given the computed profile. mode_in is to copy palette order from when relevant.*/ static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, const LodePNGColorProfile* prof) { unsigned error = 0; unsigned palettebits, palette_ok; size_t i, n; size_t numpixels = prof->numpixels; unsigned alpha = prof->alpha; unsigned key = prof->key; unsigned bits = prof->bits; mode_out->key_defined = 0; if (key && numpixels <= 16) { alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ key = 0; if (bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ } n = prof->numcolors; palettebits = n <= 2 ? 1 : (n <= 4 ? 2 : (n <= 16 ? 4 : 8)); palette_ok = n <= 256 && bits <= 8; if (numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ if (!prof->colored && bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ if (palette_ok) { const unsigned char* p = prof->palette; lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ for (i = 0; i != prof->numcolors; ++i) { error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); if (error) break; } mode_out->colortype = LCT_PALETTE; mode_out->bitdepth = palettebits; if (mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize && mode_in->bitdepth == mode_out->bitdepth) { /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ lodepng_color_mode_cleanup(mode_out); lodepng_color_mode_copy(mode_out, mode_in); } } else /*8-bit or 16-bit per channel*/ { mode_out->bitdepth = bits; mode_out->colortype = alpha ? (prof->colored ? LCT_RGBA : LCT_GREY_ALPHA) : (prof->colored ? LCT_RGB : LCT_GREY); if (key) { unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ mode_out->key_r = prof->key_r & mask; mode_out->key_g = prof->key_g & mask; mode_out->key_b = prof->key_b & mask; mode_out->key_defined = 1; } } return error; } /*Automatically chooses color type that gives smallest amount of bits in the output image, e.g. grey if there are only greyscale pixels, palette if there are less than 256 colors, color key if only single transparent color, ... Updates values of mode with a potentially smaller color model. mode_out should contain the user chosen color model, but will be overwritten with the new chosen one.*/ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const unsigned char* image, unsigned w, unsigned h, const LodePNGColorMode* mode_in) { unsigned error = 0; LodePNGColorProfile prof; lodepng_color_profile_init(&prof); error = lodepng_get_color_profile(&prof, image, w, h, mode_in); if (error) return error; return auto_choose_color_from_profile(mode_out, mode_in, &prof); } #endif /* #ifdef LODEPNG_COMPILE_ENCODER */ /* Paeth predicter, used by PNG filter type 4 The parameters are of type short, but should come from unsigned chars, the shorts are only needed to make the paeth calculation correct. */ static unsigned char paethPredictor(short a, short b, short c) { short pa = abs(b - c); short pb = abs(a - c); short pc = abs(a + b - c - c); if (pc < pa && pc < pb) return (unsigned char)c; else if (pb < pa) return (unsigned char)b; else return (unsigned char)a; } /*shared values used by multiple Adam7 related functions*/ static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ static const unsigned ADAM7_IY[7] = { 0, 0, 4, 0, 2, 0, 1 }; /*y start values*/ static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ /* Outputs various dimensions and positions in the image related to the Adam7 reduced images. passw: output containing the width of the 7 passes passh: output containing the height of the 7 passes filter_passstart: output containing the index of the start and end of each reduced image with filter bytes padded_passstart output containing the index of the start and end of each reduced image when without filter bytes but with padded scanlines passstart: output containing the index of the start and end of each reduced image without padding between scanlines, but still padding between the images w, h: width and height of non-interlaced image bpp: bits per pixel "padded" is only relevant if bpp is less than 8 and a scanline or image does not end at a full byte */ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ unsigned i; /*calculate width and height in pixels of each pass*/ for (i = 0; i != 7; ++i) { passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; if (passw[i] == 0) passh[i] = 0; if (passh[i] == 0) passw[i] = 0; } filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; for (i = 0; i != 7; ++i) { /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ filter_passstart[i + 1] = filter_passstart[i] + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); /*bits padded if needed to fill full byte at end of each scanline*/ padded_passstart[i + 1] = padded_passstart[i] + passh[i] * ((passw[i] * bpp + 7) / 8); /*only padded at end of reduced image*/ passstart[i + 1] = passstart[i] + (passh[i] * passw[i] * bpp + 7) / 8; } } #ifdef LODEPNG_COMPILE_DECODER /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG Decoder / */ /* ////////////////////////////////////////////////////////////////////////// */ /*read the information from the header and store it in the LodePNGInfo. return value is error*/ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { LodePNGInfo* info = &state->info_png; if (insize == 0 || in == 0) { CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ } if (insize < 33) { CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ } /*when decoding a new PNG image, make sure all parameters created after previous decoding are reset*/ lodepng_info_cleanup(info); lodepng_info_init(info); if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ } if (lodepng_chunk_length(in + 8) != 13) { CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ } if (!lodepng_chunk_type_equals(in + 8, "IHDR")) { CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ } /*read the values given in the header*/ *w = lodepng_read32bitInt(&in[16]); *h = lodepng_read32bitInt(&in[20]); info->color.bitdepth = in[24]; info->color.colortype = (LodePNGColorType)in[25]; info->compression_method = in[26]; info->filter_method = in[27]; info->interlace_method = in[28]; if (*w == 0 || *h == 0) { CERROR_RETURN_ERROR(state->error, 93); } if (!state->decoder.ignore_crc) { unsigned CRC = lodepng_read32bitInt(&in[29]); unsigned checksum = lodepng_crc32(&in[12], 17); if (CRC != checksum) { CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ } } /*error: only compression method 0 is allowed in the specification*/ if (info->compression_method != 0) CERROR_RETURN_ERROR(state->error, 32); /*error: only filter method 0 is allowed in the specification*/ if (info->filter_method != 0) CERROR_RETURN_ERROR(state->error, 33); /*error: only interlace methods 0 and 1 exist in the specification*/ if (info->interlace_method > 1) CERROR_RETURN_ERROR(state->error, 34); state->error = checkColorValidity(info->color.colortype, info->color.bitdepth); return state->error; } static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned char filterType, size_t length) { /* For PNG filter method 0 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, the filter works byte per byte (bytewidth = 1) precon is the previous unfiltered scanline, recon the result, scanline the current one the incoming scanlines do NOT include the filtertype byte, that one is given in the parameter filterType instead recon and scanline MAY be the same memory address! precon must be disjoint. */ size_t i; switch (filterType) { case 0: for (i = 0; i != length; ++i) recon[i] = scanline[i]; break; case 1: for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; break; case 2: if (precon) { for (i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; } else { for (i = 0; i != length; ++i) recon[i] = scanline[i]; } break; case 3: if (precon) { for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1); for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1); } else { for (i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; for (i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1); } break; case 4: if (precon) { for (i = 0; i != bytewidth; ++i) { recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ } for (i = bytewidth; i < length; ++i) { recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); } } else { for (i = 0; i != bytewidth; ++i) { recon[i] = scanline[i]; } for (i = bytewidth; i < length; ++i) { /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ recon[i] = (scanline[i] + recon[i - bytewidth]); } } break; default: return 36; /*error: unexisting filter type given*/ } return 0; } static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { /* For PNG filter method 0 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) out must have enough bytes allocated already, in must have the scanlines + 1 filtertype byte per scanline w and h are image dimensions or dimensions of reduced image, bpp is bits per pixel in and out are allowed to be the same memory address (but aren't the same size since in has the extra filter bytes) */ unsigned y; unsigned char* prevline = 0; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ size_t bytewidth = (bpp + 7) / 8; size_t linebytes = (w * bpp + 7) / 8; for (y = 0; y < h; ++y) { size_t outindex = linebytes * y; size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ unsigned char filterType = in[inindex]; CERROR_TRY_RETURN(unfilterScanline(&out[outindex], &in[inindex + 1], prevline, bytewidth, filterType, linebytes)); prevline = &out[outindex]; } return 0; } /* in: Adam7 interlaced image, with no padding bits between scanlines, but between reduced images so that each reduced image starts at a byte. out: the same pixels, but re-ordered so that they're now a non-interlaced image with size w*h bpp: bits per pixel out has the following size in bits: w * h * bpp. in is possibly bigger due to padding bits between reduced images. out must be big enough AND must be 0 everywhere if bpp < 8 in the current implementation (because that's likely a little bit faster) NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); if (bpp >= 8) { for (i = 0; i != 7; ++i) { unsigned x, y, b; size_t bytewidth = bpp / 8; for (y = 0; y < passh[i]; ++y) for (x = 0; x < passw[i]; ++x) { size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; for (b = 0; b < bytewidth; ++b) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { for (i = 0; i != 7; ++i) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for (y = 0; y < passh[i]; ++y) for (x = 0; x < passw[i]; ++x) { ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; for (b = 0; b < bpp; ++b) { unsigned char bit = readBitFromReversedStream(&ibp, in); /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ setBitOfReversedStream0(&obp, out, bit); } } } } } static void removePaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h) { /* After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers for the Adam7 code, the color convert code and the output to the user. in and out are allowed to be the same buffer, in may also be higher but still overlapping; in must have >= ilinebits*h bits, out must have >= olinebits*h bits, olinebits must be <= ilinebits also used to move bits after earlier such operations happened, e.g. in a sequence of reduced images from Adam7 only useful if (ilinebits - olinebits) is a value in the range 1..7 */ unsigned y; size_t diff = ilinebits - olinebits; size_t ibp = 0, obp = 0; /*input and output bit pointers*/ for (y = 0; y < h; ++y) { size_t x; for (x = 0; x < olinebits; ++x) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } ibp += diff; } } /*out must be buffer big enough to contain full image, and in must contain the full decompressed data from the IDAT chunks (with filter index bytes and possible padding bits) return value is error*/ static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, unsigned w, unsigned h, const LodePNGInfo* info_png) { /* This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. Steps: *) if no Adam7: 1) unfilter 2) remove padding bits (= posible extra bits per scanline if bpp < 8) *) if adam7: 1) 7x unfilter 2) 7x remove padding bits 3) Adam7_deinterlace NOTE: the in buffer will be overwritten with intermediate data! */ unsigned bpp = lodepng_get_bpp(&info_png->color); if (bpp == 0) return 31; /*error: invalid colortype*/ if (info_png->interlace_method == 0) { if (bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); } /*we can immediately filter into the out buffer, no other steps needed*/ else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); for (i = 0; i != 7; ++i) { CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, move bytes instead of bits or move not at all*/ if (bpp < 8) { /*remove padding bits in scanlines; after this there still may be padding bits between the different reduced images: each reduced image still starts nicely at a byte*/ removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, ((passw[i] * bpp + 7) / 8) * 8, passh[i]); } } Adam7_deinterlace(out, in, w, h, bpp); } return 0; } static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned pos = 0, i; if (color->palette) lodepng_free(color->palette); color->palettesize = chunkLength / 3; color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize); if (!color->palette && color->palettesize) { color->palettesize = 0; return 83; /*alloc fail*/ } if (color->palettesize > 256) return 38; /*error: palette too big*/ for (i = 0; i != color->palettesize; ++i) { color->palette[4 * i + 0] = data[pos++]; /*R*/ color->palette[4 * i + 1] = data[pos++]; /*G*/ color->palette[4 * i + 2] = data[pos++]; /*B*/ color->palette[4 * i + 3] = 255; /*alpha*/ } return 0; /* OK */ } static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned i; if (color->colortype == LCT_PALETTE) { /*error: more alpha values given than there are palette entries*/ if (chunkLength > color->palettesize) return 39; for (i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; } else if (color->colortype == LCT_GREY) { /*error: this chunk must be 2 bytes for greyscale image*/ if (chunkLength != 2) return 30; color->key_defined = 1; color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; } else if (color->colortype == LCT_RGB) { /*error: this chunk must be 6 bytes for RGB image*/ if (chunkLength != 6) return 41; color->key_defined = 1; color->key_r = 256u * data[0] + data[1]; color->key_g = 256u * data[2] + data[3]; color->key_b = 256u * data[4] + data[5]; } else return 42; /*error: tRNS chunk not allowed for other color models*/ return 0; /* OK */ } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*background color chunk (bKGD)*/ static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (info->color.colortype == LCT_PALETTE) { /*error: this chunk must be 1 byte for indexed color image*/ if (chunkLength != 1) return 43; /*error: invalid palette index, or maybe this chunk appeared before PLTE*/ if (data[0] >= info->color.palettesize) return 103; info->background_defined = 1; info->background_r = info->background_g = info->background_b = data[0]; } else if (info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { /*error: this chunk must be 2 bytes for greyscale image*/ if (chunkLength != 2) return 44; /*the values are truncated to bitdepth in the PNG file*/ info->background_defined = 1; info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; } else if (info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { /*error: this chunk must be 6 bytes for greyscale image*/ if (chunkLength != 6) return 45; /*the values are truncated to bitdepth in the PNG file*/ info->background_defined = 1; info->background_r = 256u * data[0] + data[1]; info->background_g = 256u * data[2] + data[3]; info->background_b = 256u * data[4] + data[5]; } return 0; /* OK */ } /*text chunk (tEXt)*/ static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { unsigned error = 0; char *key = 0, *str = 0; unsigned i; while (!error) /*not really a while loop, only used to break on error*/ { unsigned length, string2_begin; length = 0; while (length < chunkLength && data[length] != 0) ++length; /*even though it's not allowed by the standard, no error is thrown if there's no null termination char, if the text is empty*/ if (length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)lodepng_malloc(length + 1); if (!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for (i = 0; i != length; ++i) key[i] = (char)data[i]; string2_begin = length + 1; /*skip keyword null terminator*/ length = (unsigned)(chunkLength < string2_begin ? 0 : chunkLength - string2_begin); str = (char*)lodepng_malloc(length + 1); if (!str) CERROR_BREAK(error, 83); /*alloc fail*/ str[length] = 0; for (i = 0; i != length; ++i) str[i] = (char)data[string2_begin + i]; error = lodepng_add_text(info, key, str); break; } lodepng_free(key); lodepng_free(str); return error; } /*compressed text chunk (zTXt)*/ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; unsigned length, string2_begin; char *key = 0; ucvector decoded; ucvector_init(&decoded); while (!error) /*not really a while loop, only used to break on error*/ { for (length = 0; length < chunkLength && data[length] != 0; ++length); if (length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ if (length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)lodepng_malloc(length + 1); if (!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for (i = 0; i != length; ++i) key[i] = (char)data[i]; if (data[length + 1] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ string2_begin = length + 2; if (string2_begin > chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ length = (unsigned)chunkLength - string2_begin; /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[string2_begin]), length, zlibsettings); if (error) break; ucvector_push_back(&decoded, 0); error = lodepng_add_text(info, key, (char*)decoded.data); break; } lodepng_free(key); ucvector_cleanup(&decoded); return error; } /*international text chunk (iTXt)*/ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; unsigned length, begin, compressed; char *key = 0, *langtag = 0, *transkey = 0; ucvector decoded; ucvector_init(&decoded); /* TODO: only use in case of compressed text */ while (!error) /*not really a while loop, only used to break on error*/ { /*Quick check if the chunk length isn't too small. Even without check it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ if (chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ /*read the key*/ for (length = 0; length < chunkLength && data[length] != 0; ++length); if (length + 3 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination char, corrupt?*/ if (length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ key = (char*)lodepng_malloc(length + 1); if (!key) CERROR_BREAK(error, 83); /*alloc fail*/ key[length] = 0; for (i = 0; i != length; ++i) key[i] = (char)data[i]; /*read the compression method*/ compressed = data[length + 1]; if (data[length + 2] != 0) CERROR_BREAK(error, 72); /*the 0 byte indicating compression must be 0*/ /*even though it's not allowed by the standard, no error is thrown if there's no null termination char, if the text is empty for the next 3 texts*/ /*read the langtag*/ begin = length + 3; length = 0; for (i = begin; i < chunkLength && data[i] != 0; ++i) ++length; langtag = (char*)lodepng_malloc(length + 1); if (!langtag) CERROR_BREAK(error, 83); /*alloc fail*/ langtag[length] = 0; for (i = 0; i != length; ++i) langtag[i] = (char)data[begin + i]; /*read the transkey*/ begin += length + 1; length = 0; for (i = begin; i < chunkLength && data[i] != 0; ++i) ++length; transkey = (char*)lodepng_malloc(length + 1); if (!transkey) CERROR_BREAK(error, 83); /*alloc fail*/ transkey[length] = 0; for (i = 0; i != length; ++i) transkey[i] = (char)data[begin + i]; /*read the actual text*/ begin += length + 1; length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; if (compressed) { /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[begin]), length, zlibsettings); if (error) break; if (decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; ucvector_push_back(&decoded, 0); } else { if (!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); decoded.data[length] = 0; for (i = 0; i != length; ++i) decoded.data[i] = data[begin + i]; } error = lodepng_add_itext(info, key, langtag, transkey, (char*)decoded.data); break; } lodepng_free(key); lodepng_free(langtag); lodepng_free(transkey); ucvector_cleanup(&decoded); return error; } static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (chunkLength != 7) return 73; /*invalid tIME chunk size*/ info->time_defined = 1; info->time.year = 256u * data[0] + data[1]; info->time.month = data[2]; info->time.day = data[3]; info->time.hour = data[4]; info->time.minute = data[5]; info->time.second = data[6]; return 0; /* OK */ } static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (chunkLength != 9) return 74; /*invalid pHYs chunk size*/ info->phys_defined = 1; info->phys_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; info->phys_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; info->phys_unit = data[8]; return 0; /* OK */ } static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (chunkLength != 4) return 96; /*invalid gAMA chunk size*/ info->gama_defined = 1; info->gama_gamma = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; return 0; /* OK */ } static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (chunkLength != 32) return 97; /*invalid cHRM chunk size*/ info->chrm_defined = 1; info->chrm_white_x = 16777216u * data[0] + 65536u * data[1] + 256u * data[2] + data[3]; info->chrm_white_y = 16777216u * data[4] + 65536u * data[5] + 256u * data[6] + data[7]; info->chrm_red_x = 16777216u * data[8] + 65536u * data[9] + 256u * data[10] + data[11]; info->chrm_red_y = 16777216u * data[12] + 65536u * data[13] + 256u * data[14] + data[15]; info->chrm_green_x = 16777216u * data[16] + 65536u * data[17] + 256u * data[18] + data[19]; info->chrm_green_y = 16777216u * data[20] + 65536u * data[21] + 256u * data[22] + data[23]; info->chrm_blue_x = 16777216u * data[24] + 65536u * data[25] + 256u * data[26] + data[27]; info->chrm_blue_y = 16777216u * data[28] + 65536u * data[29] + 256u * data[30] + data[31]; return 0; /* OK */ } static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if (chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/ info->srgb_defined = 1; info->srgb_intent = data[0]; return 0; /* OK */ } static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; unsigned length, string2_begin; ucvector decoded; info->iccp_defined = 1; if (info->iccp_name) lodepng_clear_icc(info); for (length = 0; length < chunkLength && data[length] != 0; ++length); if (length + 2 >= chunkLength) return 75; /*no null termination, corrupt?*/ if (length < 1 || length > 79) return 89; /*keyword too short or long*/ info->iccp_name = (char*)lodepng_malloc(length + 1); if (!info->iccp_name) return 83; /*alloc fail*/ info->iccp_name[length] = 0; for (i = 0; i != length; ++i) info->iccp_name[i] = (char)data[i]; if (data[length + 1] != 0) return 72; /*the 0 byte indicating compression must be 0*/ string2_begin = length + 2; if (string2_begin > chunkLength) return 75; /*no null termination, corrupt?*/ length = (unsigned)chunkLength - string2_begin; ucvector_init(&decoded); error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[string2_begin]), length, zlibsettings); if (!error) { info->iccp_profile_size = decoded.size; info->iccp_profile = (unsigned char*)lodepng_malloc(decoded.size); if (info->iccp_profile) { memcpy(info->iccp_profile, decoded.data, decoded.size); } else { error = 83; /* alloc fail */ } } ucvector_cleanup(&decoded); return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { unsigned char IEND = 0; const unsigned char* chunk; size_t i; ucvector idat; /*the data from idat chunks*/ ucvector scanlines; size_t predict; size_t outsize = 0; /*for unknown chunk order*/ unsigned unknown = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS unsigned critical_pos = 1; /*1 = after IHDR, 2 = after PLTE, 3 = after IDAT*/ #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*provide some proper output values if error will happen*/ *out = 0; state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ if (state->error) return; if (lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) { CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ } ucvector_init(&idat); chunk = &in[33]; /*first byte of the first chunk after the header*/ /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer*/ while (!IEND && !state->error) { unsigned chunkLength; const unsigned char* data; /*the data in the chunk*/ /*error: size of the in buffer too small to contain next chunk*/ if ((size_t)((chunk - in) + 12) > insize || chunk < in) { if (state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 30); } /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ chunkLength = lodepng_chunk_length(chunk); /*error: chunk length larger than the max PNG chunk size*/ if (chunkLength > 2147483647) { if (state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 63); } if ((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) { CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ } data = lodepng_chunk_data_const(chunk); unknown = 0; /*IDAT chunk, containing compressed image data*/ if (lodepng_chunk_type_equals(chunk, "IDAT")) { size_t oldsize = idat.size; size_t newsize; if (lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); if (!ucvector_resize(&idat, newsize)) CERROR_BREAK(state->error, 83 /*alloc fail*/); for (i = 0; i != chunkLength; ++i) idat.data[oldsize + i] = data[i]; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 3; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } /*IEND chunk*/ else if (lodepng_chunk_type_equals(chunk, "IEND")) { IEND = 1; } /*palette chunk (PLTE)*/ else if (lodepng_chunk_type_equals(chunk, "PLTE")) { state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); if (state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 2; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that affects the alpha channel of pixels. */ else if (lodepng_chunk_type_equals(chunk, "tRNS")) { state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); if (state->error) break; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*background color chunk (bKGD)*/ else if (lodepng_chunk_type_equals(chunk, "bKGD")) { state->error = readChunk_bKGD(&state->info_png, data, chunkLength); if (state->error) break; } /*text chunk (tEXt)*/ else if (lodepng_chunk_type_equals(chunk, "tEXt")) { if (state->decoder.read_text_chunks) { state->error = readChunk_tEXt(&state->info_png, data, chunkLength); if (state->error) break; } } /*compressed text chunk (zTXt)*/ else if (lodepng_chunk_type_equals(chunk, "zTXt")) { if (state->decoder.read_text_chunks) { state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if (state->error) break; } } /*international text chunk (iTXt)*/ else if (lodepng_chunk_type_equals(chunk, "iTXt")) { if (state->decoder.read_text_chunks) { state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if (state->error) break; } } else if (lodepng_chunk_type_equals(chunk, "tIME")) { state->error = readChunk_tIME(&state->info_png, data, chunkLength); if (state->error) break; } else if (lodepng_chunk_type_equals(chunk, "pHYs")) { state->error = readChunk_pHYs(&state->info_png, data, chunkLength); if (state->error) break; } else if (lodepng_chunk_type_equals(chunk, "gAMA")) { state->error = readChunk_gAMA(&state->info_png, data, chunkLength); if (state->error) break; } else if (lodepng_chunk_type_equals(chunk, "cHRM")) { state->error = readChunk_cHRM(&state->info_png, data, chunkLength); if (state->error) break; } else if (lodepng_chunk_type_equals(chunk, "sRGB")) { state->error = readChunk_sRGB(&state->info_png, data, chunkLength); if (state->error) break; } else if (lodepng_chunk_type_equals(chunk, "iCCP")) { state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if (state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ if (!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) { CERROR_BREAK(state->error, 69); } unknown = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if (state->decoder.remember_unknown_chunks) { state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); if (state->error) break; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } if (!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ { if (lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ } if (!IEND) chunk = lodepng_chunk_next_const(chunk); } ucvector_init(&scanlines); /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. If the decompressed size does not match the prediction, the image must be corrupt.*/ if (state->info_png.interlace_method == 0) { predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color); } else { /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ const LodePNGColorMode* color = &state->info_png.color; predict = 0; predict += lodepng_get_raw_size_idat((*w + 7) >> 3, (*h + 7) >> 3, color); if (*w > 4) predict += lodepng_get_raw_size_idat((*w + 3) >> 3, (*h + 7) >> 3, color); predict += lodepng_get_raw_size_idat((*w + 3) >> 2, (*h + 3) >> 3, color); if (*w > 2) predict += lodepng_get_raw_size_idat((*w + 1) >> 2, (*h + 3) >> 2, color); predict += lodepng_get_raw_size_idat((*w + 1) >> 1, (*h + 1) >> 2, color); if (*w > 1) predict += lodepng_get_raw_size_idat((*w + 0) >> 1, (*h + 1) >> 1, color); predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color); } if (!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ if (!state->error) { state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, idat.size, &state->decoder.zlibsettings); if (!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ } ucvector_cleanup(&idat); if (!state->error) { outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); *out = (unsigned char*)lodepng_malloc(outsize); if (!*out) state->error = 83; /*alloc fail*/ } if (!state->error) { for (i = 0; i < outsize; i++) (*out)[i] = 0; state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png); } ucvector_cleanup(&scanlines); } unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, const unsigned char* in, size_t insize) { *out = 0; decodeGeneric(out, w, h, state, in, insize); if (state->error) return state->error; if (!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) { /*same color type, no copying or converting of data needed*/ /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype the raw image has to the end user*/ if (!state->decoder.color_convert) { state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); if (state->error) return state->error; } } else { /*color conversion needed; sort of copy of the data*/ unsigned char* data = *out; size_t outsize; /*TODO: check if this works according to the statement in the documentation: "The converter can convert from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ if (!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) && !(state->info_raw.bitdepth == 8)) { return 56; /*unsupported color mode conversion*/ } outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); *out = (unsigned char*)lodepng_malloc(outsize); if (!(*out)) { state->error = 83; /*alloc fail*/ } else state->error = lodepng_convert(*out, data, &state->info_raw, &state->info_png.color, *w, *h); lodepng_free(data); } return state->error; } unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; error = lodepng_decode(out, w, h, &state, in, insize); lodepng_state_cleanup(&state); return error; } unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); } unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer = 0; size_t buffersize; unsigned error; error = lodepng_load_file(&buffer, &buffersize, filename); if (!error) error = lodepng_decode_memory(out, w, h, buffer, buffersize, colortype, bitdepth); lodepng_free(buffer); return error; } unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); } unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { settings->color_convert = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS settings->read_text_chunks = 1; settings->remember_unknown_chunks = 0; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ settings->ignore_crc = 0; settings->ignore_critical = 0; settings->ignore_end = 0; lodepng_decompress_settings_init(&settings->zlibsettings); } #endif /*LODEPNG_COMPILE_DECODER*/ #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) void lodepng_state_init(LodePNGState* state) { #ifdef LODEPNG_COMPILE_DECODER lodepng_decoder_settings_init(&state->decoder); #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER lodepng_encoder_settings_init(&state->encoder); #endif /*LODEPNG_COMPILE_ENCODER*/ lodepng_color_mode_init(&state->info_raw); lodepng_info_init(&state->info_png); state->error = 1; } void lodepng_state_cleanup(LodePNGState* state) { lodepng_color_mode_cleanup(&state->info_raw); lodepng_info_cleanup(&state->info_png); } void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { lodepng_state_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->info_raw); lodepng_info_init(&dest->info_png); dest->error = lodepng_color_mode_copy(&dest->info_raw, &source->info_raw); if (dest->error) return; dest->error = lodepng_info_copy(&dest->info_png, &source->info_png); if (dest->error) return; } #endif /* defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) */ #ifdef LODEPNG_COMPILE_ENCODER /* ////////////////////////////////////////////////////////////////////////// */ /* / PNG Encoder / */ /* ////////////////////////////////////////////////////////////////////////// */ /*chunkName must be string of 4 characters*/ static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) { CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); out->allocsize = out->size; /*fix the allocsize again*/ return 0; } static void writeSignature(ucvector* out) { /*8 bytes PNG signature, aka the magic bytes*/ ucvector_push_back(out, 137); ucvector_push_back(out, 80); ucvector_push_back(out, 78); ucvector_push_back(out, 71); ucvector_push_back(out, 13); ucvector_push_back(out, 10); ucvector_push_back(out, 26); ucvector_push_back(out, 10); } static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { unsigned error = 0; ucvector header; ucvector_init(&header); lodepng_add32bitInt(&header, w); /*width*/ lodepng_add32bitInt(&header, h); /*height*/ ucvector_push_back(&header, (unsigned char)bitdepth); /*bit depth*/ ucvector_push_back(&header, (unsigned char)colortype); /*color type*/ ucvector_push_back(&header, 0); /*compression method*/ ucvector_push_back(&header, 0); /*filter method*/ ucvector_push_back(&header, interlace_method); /*interlace method*/ error = addChunk(out, "IHDR", header.data, header.size); ucvector_cleanup(&header); return error; } static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector PLTE; ucvector_init(&PLTE); for (i = 0; i != info->palettesize * 4; ++i) { /*add all channels except alpha channel*/ if (i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); } error = addChunk(out, "PLTE", PLTE.data, PLTE.size); ucvector_cleanup(&PLTE); return error; } static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector tRNS; ucvector_init(&tRNS); if (info->colortype == LCT_PALETTE) { size_t amount = info->palettesize; /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ for (i = info->palettesize; i != 0; --i) { if (info->palette[4 * (i - 1) + 3] == 255) --amount; else break; } /*add only alpha channel*/ for (i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); } else if (info->colortype == LCT_GREY) { if (info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); } } else if (info->colortype == LCT_RGB) { if (info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_g & 255)); ucvector_push_back(&tRNS, (unsigned char)(info->key_b >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_b & 255)); } } error = addChunk(out, "tRNS", tRNS.data, tRNS.size); ucvector_cleanup(&tRNS); return error; } static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, LodePNGCompressSettings* zlibsettings) { ucvector zlibdata; unsigned error = 0; /*compress with the Zlib compressor*/ ucvector_init(&zlibdata); error = zlib_compress(&zlibdata.data, &zlibdata.size, data, datasize, zlibsettings); if (!error) error = addChunk(out, "IDAT", zlibdata.data, zlibdata.size); ucvector_cleanup(&zlibdata); return error; } static unsigned addChunk_IEND(ucvector* out) { unsigned error = 0; error = addChunk(out, "IEND", 0, 0); return error; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { unsigned error = 0; size_t i; ucvector text; ucvector_init(&text); for (i = 0; keyword[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)keyword[i]); if (i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&text, 0); /*0 termination char*/ for (i = 0; textstring[i] != 0; ++i) ucvector_push_back(&text, (unsigned char)textstring[i]); error = addChunk(out, "tEXt", text.data, text.size); ucvector_cleanup(&text); return error; } static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data, compressed; size_t i, textsize = strlen(textstring); ucvector_init(&data); ucvector_init(&compressed); for (i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); if (i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*0 termination char*/ ucvector_push_back(&data, 0); /*compression method: 0*/ error = zlib_compress(&compressed.data, &compressed.size, (unsigned char*)textstring, textsize, zlibsettings); if (!error) { for (i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); error = addChunk(out, "zTXt", data.data, data.size); } ucvector_cleanup(&compressed); ucvector_cleanup(&data); return error; } static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data; size_t i, textsize = strlen(textstring); ucvector_init(&data); for (i = 0; keyword[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)keyword[i]); if (i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*null termination char*/ ucvector_push_back(&data, compressed ? 1 : 0); /*compression flag*/ ucvector_push_back(&data, 0); /*compression method*/ for (i = 0; langtag[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)langtag[i]); ucvector_push_back(&data, 0); /*null termination char*/ for (i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]); ucvector_push_back(&data, 0); /*null termination char*/ if (compressed) { ucvector compressed_data; ucvector_init(&compressed_data); error = zlib_compress(&compressed_data.data, &compressed_data.size, (unsigned char*)textstring, textsize, zlibsettings); if (!error) { for (i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); } ucvector_cleanup(&compressed_data); } else /*not compressed*/ { for (i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]); } if (!error) error = addChunk(out, "iTXt", data.data, data.size); ucvector_cleanup(&data); return error; } static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector bKGD; ucvector_init(&bKGD); if (info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); } else if (info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255)); } else if (info->color.colortype == LCT_PALETTE) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/ } error = addChunk(out, "bKGD", bKGD.data, bKGD.size); ucvector_cleanup(&bKGD); return error; } static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { unsigned error = 0; unsigned char* data = (unsigned char*)lodepng_malloc(7); if (!data) return 83; /*alloc fail*/ data[0] = (unsigned char)(time->year >> 8); data[1] = (unsigned char)(time->year & 255); data[2] = (unsigned char)time->month; data[3] = (unsigned char)time->day; data[4] = (unsigned char)time->hour; data[5] = (unsigned char)time->minute; data[6] = (unsigned char)time->second; error = addChunk(out, "tIME", data, 7); lodepng_free(data); return error; } static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); lodepng_add32bitInt(&data, info->phys_x); lodepng_add32bitInt(&data, info->phys_y); ucvector_push_back(&data, info->phys_unit); error = addChunk(out, "pHYs", data.data, data.size); ucvector_cleanup(&data); return error; } static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); lodepng_add32bitInt(&data, info->gama_gamma); error = addChunk(out, "gAMA", data.data, data.size); ucvector_cleanup(&data); return error; } static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); lodepng_add32bitInt(&data, info->chrm_white_x); lodepng_add32bitInt(&data, info->chrm_white_y); lodepng_add32bitInt(&data, info->chrm_red_x); lodepng_add32bitInt(&data, info->chrm_red_y); lodepng_add32bitInt(&data, info->chrm_green_x); lodepng_add32bitInt(&data, info->chrm_green_y); lodepng_add32bitInt(&data, info->chrm_blue_x); lodepng_add32bitInt(&data, info->chrm_blue_y); error = addChunk(out, "cHRM", data.data, data.size); ucvector_cleanup(&data); return error; } static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) { unsigned char data = info->srgb_intent; return addChunk(out, "sRGB", &data, 1); } static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data, compressed; size_t i; ucvector_init(&data); ucvector_init(&compressed); for (i = 0; info->iccp_name[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)info->iccp_name[i]); if (i < 1 || i > 79) return 89; /*error: invalid keyword size*/ ucvector_push_back(&data, 0); /*0 termination char*/ ucvector_push_back(&data, 0); /*compression method: 0*/ error = zlib_compress(&compressed.data, &compressed.size, info->iccp_profile, info->iccp_profile_size, zlibsettings); if (!error) { for (i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); error = addChunk(out, "iCCP", data.data, data.size); } ucvector_cleanup(&compressed); ucvector_cleanup(&data); return error; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, size_t length, size_t bytewidth, unsigned char filterType) { size_t i; switch (filterType) { case 0: /*None*/ for (i = 0; i != length; ++i) out[i] = scanline[i]; break; case 1: /*Sub*/ for (i = 0; i != bytewidth; ++i) out[i] = scanline[i]; for (i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; break; case 2: /*Up*/ if (prevline) { for (i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; } else { for (i = 0; i != length; ++i) out[i] = scanline[i]; } break; case 3: /*Average*/ if (prevline) { for (i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); for (i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); } else { for (i = 0; i != bytewidth; ++i) out[i] = scanline[i]; for (i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); } break; case 4: /*Paeth*/ if (prevline) { /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ for (i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); for (i = bytewidth; i < length; ++i) { out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); } } else { for (i = 0; i != bytewidth; ++i) out[i] = scanline[i]; /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ for (i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); } break; default: return; /*unexisting filter type given*/ } } /* log2 approximation. A slight bit faster than std::log. */ static float flog2(float f) { float result = 0; while (f > 32) { result += 4; f /= 16; } while (f > 2) { ++result; f /= 2; } return result + 1.442695f * (f * f * f / 3 - 3 * f * f / 2 + 3 * f - 1.83333f); } static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) { /* For PNG filter method 0 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are the scanlines with 1 extra byte per scanline */ unsigned bpp = lodepng_get_bpp(info); /*the width of a scanline in bytes, not including the filter type*/ size_t linebytes = (w * bpp + 7) / 8; /*bytewidth is used for filtering, is 1 when bpp < 8, number of bytes per pixel otherwise*/ size_t bytewidth = (bpp + 7) / 8; const unsigned char* prevline = 0; unsigned x, y; unsigned error = 0; LodePNGFilterStrategy strategy = settings->filter_strategy; /* There is a heuristic called the minimum sum of absolute differences heuristic, suggested by the PNG standard: * If the image type is Palette, or the bit depth is smaller than 8, then do not filter the image (i.e. use fixed filtering, with the filter None). * (The other case) If the image type is Grayscale or RGB (with or without Alpha), and the bit depth is not smaller than 8, then use adaptive filtering heuristic as follows: independently for each row, apply all five filters and select the filter that produces the smallest sum of absolute values per row. This heuristic is used if filter strategy is LFS_MINSUM and filter_palette_zero is true. If filter_palette_zero is true and filter_strategy is not LFS_MINSUM, the above heuristic is followed, but for "the other case", whatever strategy filter_strategy is set to instead of the minimum sum heuristic is used. */ if (settings->filter_palette_zero && (info->colortype == LCT_PALETTE || info->bitdepth < 8)) strategy = LFS_ZERO; if (bpp == 0) return 31; /*error: invalid color type*/ if (strategy == LFS_ZERO) { for (y = 0; y != h; ++y) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; out[outindex] = 0; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); prevline = &in[inindex]; } } else if (strategy == LFS_MINSUM) { /*adaptive filtering*/ size_t sum[5]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned char type, bestType = 0; for (type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if (!attempt[type]) return 83; /*alloc fail*/ } if (!error) { for (y = 0; y != h; ++y) { /*try the 5 filter types*/ for (type = 0; type != 5; ++type) { filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); /*calculate the sum of the result*/ sum[type] = 0; if (type == 0) { for (x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]); } else { for (x = 0; x != linebytes; ++x) { /*For differences, each byte should be treated as signed, values above 127 are negative (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. This means filtertype 0 is almost never chosen, but that is justified.*/ unsigned char s = attempt[type][x]; sum[type] += s < 128 ? s : (255U - s); } } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ if (type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } } prevline = &in[y * linebytes]; /*now fill the out values*/ out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for (x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; } } for (type = 0; type != 5; ++type) lodepng_free(attempt[type]); } else if (strategy == LFS_ENTROPY) { float sum[5]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ float smallest = 0; unsigned type, bestType = 0; unsigned count[256]; for (type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if (!attempt[type]) return 83; /*alloc fail*/ } for (y = 0; y != h; ++y) { /*try the 5 filter types*/ for (type = 0; type != 5; ++type) { filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); for (x = 0; x != 256; ++x) count[x] = 0; for (x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; ++count[type]; /*the filter type itself is part of the scanline*/ sum[type] = 0; for (x = 0; x != 256; ++x) { float p = count[x] / (float)(linebytes + 1); sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ if (type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } } prevline = &in[y * linebytes]; /*now fill the out values*/ out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for (x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; } for (type = 0; type != 5; ++type) lodepng_free(attempt[type]); } else if (strategy == LFS_PREDEFINED) { for (y = 0; y != h; ++y) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; unsigned char type = settings->predefined_filters[y]; out[outindex] = type; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); prevline = &in[inindex]; } } else if (strategy == LFS_BRUTE_FORCE) { /*brute force filter chooser. deflate the scanline after every filter attempt to see which one deflates best. This is very slow and gives only slightly smaller, sometimes even larger, result*/ size_t size[5]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned type = 0, bestType = 0; unsigned char* dummy; LodePNGCompressSettings zlibsettings = settings->zlibsettings; /*use fixed tree on the attempts so that the tree is not adapted to the filtertype on purpose, to simulate the true case where the tree is the same for the whole image. Sometimes it gives better result with dynamic tree anyway. Using the fixed tree sometimes gives worse, but in rare cases better compression. It does make this a bit less slow, so it's worth doing this.*/ zlibsettings.btype = 1; /*a custom encoder likely doesn't read the btype setting and is optimized for complete PNG images only, so disable it*/ zlibsettings.custom_zlib = 0; zlibsettings.custom_deflate = 0; for (type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if (!attempt[type]) return 83; /*alloc fail*/ } for (y = 0; y != h; ++y) /*try the 5 filter types*/ { for (type = 0; type != 5; ++type) { unsigned testsize = (unsigned)linebytes; /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); size[type] = 0; dummy = 0; zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); lodepng_free(dummy); /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ if (type == 0 || size[type] < smallest) { bestType = type; smallest = size[type]; } } prevline = &in[y * linebytes]; out[y * (linebytes + 1)] = bestType; /*the first byte of a scanline will be the filter type*/ for (x = 0; x != linebytes; ++x) out[y * (linebytes + 1) + 1 + x] = attempt[bestType][x]; } for (type = 0; type != 5; ++type) lodepng_free(attempt[type]); } else return 88; /* unknown filter strategy */ return error; } static void addPaddingBits(unsigned char* out, const unsigned char* in, size_t olinebits, size_t ilinebits, unsigned h) { /*The opposite of the removePaddingBits function olinebits must be >= ilinebits*/ unsigned y; size_t diff = olinebits - ilinebits; size_t obp = 0, ibp = 0; /*bit pointers*/ for (y = 0; y != h; ++y) { size_t x; for (x = 0; x < ilinebits; ++x) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } /*obp += diff; --> no, fill in some value in the padding bits too, to avoid "Use of uninitialised value of size ###" warning from valgrind*/ for (x = 0; x != diff; ++x) setBitOfReversedStream(&obp, out, 0); } } /* in: non-interlaced image with size w*h out: the same pixels, but re-ordered according to PNG's Adam7 interlacing, with no padding bits between scanlines, but between reduced images so that each reduced image starts at a byte. bpp: bits per pixel there are no padding bits, not between scanlines, not between reduced images in has the following size in bits: w * h * bpp. out is possibly bigger due to padding bits between reduced images NOTE: comments about padding bits are only relevant if bpp < 8 */ static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); if (bpp >= 8) { for (i = 0; i != 7; ++i) { unsigned x, y, b; size_t bytewidth = bpp / 8; for (y = 0; y < passh[i]; ++y) for (x = 0; x < passw[i]; ++x) { size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; for (b = 0; b < bytewidth; ++b) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { for (i = 0; i != 7; ++i) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for (y = 0; y < passh[i]; ++y) for (x = 0; x < passw[i]; ++x) { ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); for (b = 0; b < bpp; ++b) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } } } } } /*out must be buffer big enough to contain uncompressed IDAT chunk data, and in must contain the full image. return value is error**/ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, unsigned w, unsigned h, const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { /* This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter *) if adam7: 1) Adam7_interlace 2) 7x add padding bits 3) 7x filter */ unsigned bpp = lodepng_get_bpp(&info_png->color); unsigned error = 0; if (info_png->interlace_method == 0) { *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ *out = (unsigned char*)lodepng_malloc(*outsize); if (!(*out) && (*outsize)) error = 83; /*alloc fail*/ if (!error) { /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ if (bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8)); if (!padded) error = 83; /*alloc fail*/ if (!error) { addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); error = filter(*out, padded, w, h, &info_png->color, settings); } lodepng_free(padded); } else { /*we can immediately filter into the out buffer, no other steps needed*/ error = filter(*out, in, w, h, &info_png->color, settings); } } } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned char* adam7; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); *outsize = filter_passstart[7]; /*image size plus an extra byte per scanline + possible padding bits*/ *out = (unsigned char*)lodepng_malloc(*outsize); if (!(*out)) error = 83; /*alloc fail*/ adam7 = (unsigned char*)lodepng_malloc(passstart[7]); if (!adam7 && passstart[7]) error = 83; /*alloc fail*/ if (!error) { unsigned i; Adam7_interlace(adam7, in, w, h, bpp); for (i = 0; i != 7; ++i) { if (bpp < 8) { unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); if (!padded) ERROR_BREAK(83); /*alloc fail*/ addPaddingBits(padded, &adam7[passstart[i]], ((passw[i] * bpp + 7) / 8) * 8, passw[i] * bpp, passh[i]); error = filter(&(*out)[filter_passstart[i]], padded, passw[i], passh[i], &info_png->color, settings); lodepng_free(padded); } else { error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], passw[i], passh[i], &info_png->color, settings); } if (error) break; } } lodepng_free(adam7); } return error; } /* palette must have 4 * palettesize bytes allocated, and given in format RGBARGBARGBARGBA... returns 0 if the palette is opaque, returns 1 if the palette has a single color with alpha 0 ==> color key returns 2 if the palette is semi-translucent. */ static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) { size_t i; unsigned key = 0; unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ for (i = 0; i != palettesize; ++i) { if (!key && palette[4 * i + 3] == 0) { r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; key = 1; i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ } else if (palette[4 * i + 3] != 255) return 2; /*when key, no opaque RGB may have key's RGB*/ else if (key && r == palette[i * 4 + 0] && g == palette[i * 4 + 1] && b == palette[i * 4 + 2]) return 2; } return key; } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) { unsigned char* inchunk = data; while ((size_t)(inchunk - data) < datasize) { CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); out->allocsize = out->size; /*fix the allocsize again*/ inchunk = lodepng_chunk_next(inchunk); } return 0; } static unsigned isGreyICCProfile(const unsigned char* profile, unsigned size) { /* It is a grey profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19 are "RGB ". We do not perform any full parsing of the ICC profile here, other than check those 4 bytes to grayscale profile. Other than that, validity of the profile is not checked. This is needed only because the PNG specification requires using a non-grey color model if there is an ICC profile with "RGB " (sadly limiting compression opportunities if the input data is greyscale RGB data), and requires using a grey color model if it is "GRAY". */ if (size < 20) return 0; return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y'; } static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) { /* See comment in isGreyICCProfile*/ if (size < 20) return 0; return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' '; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGState* state) { unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ size_t datasize = 0; ucvector outv; LodePNGInfo info; ucvector_init(&outv); lodepng_info_init(&info); /*provide some proper output values if error will happen*/ *out = 0; *outsize = 0; state->error = 0; /*check input values validity*/ if ((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette) && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) { state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ goto cleanup; } if (state->encoder.zlibsettings.btype > 2) { state->error = 61; /*error: unexisting btype*/ goto cleanup; } if (state->info_png.interlace_method > 1) { state->error = 71; /*error: unexisting interlace mode*/ goto cleanup; } state->error = checkColorValidity(state->info_png.color.colortype, state->info_png.color.bitdepth); if (state->error) goto cleanup; /*error: unexisting color type given*/ state->error = checkColorValidity(state->info_raw.colortype, state->info_raw.bitdepth); if (state->error) goto cleanup; /*error: unexisting color type given*/ /* color convert and compute scanline filter types */ lodepng_info_copy(&info, &state->info_png); if (state->encoder.auto_convert) { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if (state->info_png.background_defined) { unsigned bg_r = state->info_png.background_r; unsigned bg_g = state->info_png.background_g; unsigned bg_b = state->info_png.background_b; unsigned r = 0, g = 0, b = 0; LodePNGColorProfile prof; LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGB, 16); lodepng_convert_rgb(&r, &g, &b, bg_r, bg_g, bg_b, &mode16, &state->info_png.color); lodepng_color_profile_init(&prof); state->error = lodepng_get_color_profile(&prof, image, w, h, &state->info_raw); if (state->error) goto cleanup; lodepng_color_profile_add(&prof, r, g, b, 65535); state->error = auto_choose_color_from_profile(&info.color, &state->info_raw, &prof); if (state->error) goto cleanup; if (lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b, bg_r, bg_g, bg_b, &info.color, &state->info_png.color)) { state->error = 104; goto cleanup; } } else #endif /* LODEPNG_COMPILE_ANCILLARY_CHUNKS */ { state->error = lodepng_auto_choose_color(&info.color, image, w, h, &state->info_raw); if (state->error) goto cleanup; } } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS if (state->info_png.iccp_defined) { unsigned grey_icc = isGreyICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size); unsigned grey_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA; /* TODO: perhaps instead of giving errors or less optimal compression, we can automatically modify the ICC profile here to say "GRAY" or "RGB " to match the PNG color type, unless this will require non trivial changes to the rest of the ICC profile */ if (!grey_icc && !isRGBICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size)) { state->error = 100; /* Disallowed profile color type for PNG */ goto cleanup; } if (!state->encoder.auto_convert && grey_icc != grey_png) { /* Non recoverable: encoder not allowed to convert color type, and requested color type not compatible with ICC color type */ state->error = 101; goto cleanup; } if (grey_icc && !grey_png) { /* Non recoverable: trying to set greyscale ICC profile while colored pixels were given */ state->error = 102; goto cleanup; /* NOTE: this relies on the fact that lodepng_auto_choose_color never returns palette for greyscale pixels */ } if (!grey_icc && grey_png) { /* Recoverable but an unfortunate loss in compression density: We have greyscale pixels but are forced to store them in more expensive RGB format that will repeat each value 3 times because the PNG spec does not allow an RGB ICC profile with internal greyscale color data */ if (info.color.colortype == LCT_GREY) info.color.colortype = LCT_RGB; if (info.color.colortype == LCT_GREY_ALPHA) info.color.colortype = LCT_RGBA; if (info.color.bitdepth < 8) info.color.bitdepth = 8; } } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ if (!lodepng_color_mode_equal(&state->info_raw, &info.color)) { unsigned char* converted; size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; converted = (unsigned char*)lodepng_malloc(size); if (!converted && size) state->error = 83; /*alloc fail*/ if (!state->error) { state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); } if (!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); lodepng_free(converted); if (state->error) goto cleanup; } else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); /* output all PNG chunks */ { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS size_t i; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*write signature and chunks*/ writeSignature(&outv); /*IHDR*/ addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*unknown chunks between IHDR and PLTE*/ if (info.unknown_chunks_data[0]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); if (state->error) goto cleanup; } /*color profile chunks must come before PLTE */ if (info.iccp_defined) addChunk_iCCP(&outv, &info, &state->encoder.zlibsettings); if (info.srgb_defined) addChunk_sRGB(&outv, &info); if (info.gama_defined) addChunk_gAMA(&outv, &info); if (info.chrm_defined) addChunk_cHRM(&outv, &info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*PLTE*/ if (info.color.colortype == LCT_PALETTE) { addChunk_PLTE(&outv, &info.color); } if (state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { addChunk_PLTE(&outv, &info.color); } /*tRNS*/ if (info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) { addChunk_tRNS(&outv, &info.color); } if ((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) { addChunk_tRNS(&outv, &info.color); } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*bKGD (must come between PLTE and the IDAt chunks*/ if (info.background_defined) { state->error = addChunk_bKGD(&outv, &info); if (state->error) goto cleanup; } /*pHYs (must come before the IDAT chunks)*/ if (info.phys_defined) addChunk_pHYs(&outv, &info); /*unknown chunks between PLTE and IDAT*/ if (info.unknown_chunks_data[1]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); if (state->error) goto cleanup; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*IDAT (multiple IDAT chunks must be consecutive)*/ state->error = addChunk_IDAT(&outv, data, datasize, &state->encoder.zlibsettings); if (state->error) goto cleanup; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*tIME*/ if (info.time_defined) addChunk_tIME(&outv, &info.time); /*tEXt and/or zTXt*/ for (i = 0; i != info.text_num; ++i) { if (strlen(info.text_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } if (strlen(info.text_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } if (state->encoder.text_compression) { addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); } else { addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); } } /*LodePNG version id in text chunk*/ if (state->encoder.add_id) { unsigned already_added_id_text = 0; for (i = 0; i != info.text_num; ++i) { if (!strcmp(info.text_keys[i], "LodePNG")) { already_added_id_text = 1; break; } } if (already_added_id_text == 0) { addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ } } /*iTXt*/ for (i = 0; i != info.itext_num; ++i) { if (strlen(info.itext_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } if (strlen(info.itext_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } addChunk_iTXt(&outv, state->encoder.text_compression, info.itext_keys[i], info.itext_langtags[i], info.itext_transkeys[i], info.itext_strings[i], &state->encoder.zlibsettings); } /*unknown chunks between IDAT and IEND*/ if (info.unknown_chunks_data[2]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); if (state->error) goto cleanup; } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ addChunk_IEND(&outv); } cleanup: lodepng_info_cleanup(&info); lodepng_free(data); /*instead of cleaning the vector up, give it to the output*/ *out = outv.data; *outsize = outv.size; return state->error; } unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; state.info_png.color.colortype = colortype; state.info_png.color.bitdepth = bitdepth; lodepng_encode(out, outsize, image, w, h, &state); error = state.error; lodepng_state_cleanup(&state); return error; } unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); if (!error) error = lodepng_save_file(buffer, buffersize, filename); lodepng_free(buffer); return error; } unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); } unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { lodepng_compress_settings_init(&settings->zlibsettings); settings->filter_palette_zero = 1; settings->filter_strategy = LFS_MINSUM; settings->auto_convert = 1; settings->force_palette = 0; settings->predefined_filters = 0; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS settings->add_id = 0; settings->text_compression = 1; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } #endif /*LODEPNG_COMPILE_ENCODER*/ #endif /*LODEPNG_COMPILE_PNG*/ #ifdef LODEPNG_COMPILE_ERROR_TEXT /* This returns the description of a numerical error code in English. This is also the documentation of all the error codes. */ const char* lodepng_error_text(unsigned code) { switch (code) { case 0: return "no error, everything went ok"; case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ case 11: return "error in code tree made it jump outside of huffman tree"; /*while huffman decoding*/ case 13: return "problem while processing dynamic deflate block"; case 14: return "problem while processing dynamic deflate block"; case 15: return "problem while processing dynamic deflate block"; case 16: return "unexisting code while processing dynamic deflate block"; case 17: return "end of out buffer memory reached while inflating"; case 18: return "invalid distance code while inflating"; case 19: return "end of out buffer memory reached while inflating"; case 20: return "invalid deflate block BTYPE encountered while decoding"; case 21: return "NLEN is not ones complement of LEN in a deflate block"; /*end of out buffer memory reached while inflating: This can happen if the inflated deflate data is longer than the amount of bytes required to fill up all the pixels of the image, given the color depth and image dimensions. Something that doesn't happen in a normal, well encoded, PNG image.*/ case 22: return "end of out buffer memory reached while inflating"; case 23: return "end of in buffer memory reached while inflating"; case 24: return "invalid FCHECK in zlib header"; case 25: return "invalid compression method in zlib header"; case 26: return "FDICT encountered in zlib header while it's not used for PNG"; case 27: return "PNG file is smaller than a PNG header"; /*Checks the magic file header, the first 8 bytes of the PNG file*/ case 28: return "incorrect PNG signature, it's no PNG or corrupted"; case 29: return "first chunk is not the header chunk"; case 30: return "chunk length too large, chunk broken off at end of file"; case 31: return "illegal PNG color type or bpp"; case 32: return "illegal PNG compression method"; case 33: return "illegal PNG filter method"; case 34: return "illegal PNG interlace method"; case 35: return "chunk length of a chunk is too large or the chunk too small"; case 36: return "illegal PNG filter type encountered"; case 37: return "illegal bit depth for this color type given"; case 38: return "the palette is too big"; /*more than 256 colors*/ case 39: return "tRNS chunk before PLTE or has more entries than palette size"; case 40: return "tRNS chunk has wrong size for greyscale image"; case 41: return "tRNS chunk has wrong size for RGB image"; case 42: return "tRNS chunk appeared while it was not allowed for this color type"; case 43: return "bKGD chunk has wrong size for palette image"; case 44: return "bKGD chunk has wrong size for greyscale image"; case 45: return "bKGD chunk has wrong size for RGB image"; case 48: return "empty input buffer given to decoder. Maybe caused by non-existing file?"; case 49: return "jumped past memory while generating dynamic huffman tree"; case 50: return "jumped past memory while generating dynamic huffman tree"; case 51: return "jumped past memory while inflating huffman block"; case 52: return "jumped past memory while inflating"; case 53: return "size of zlib data too small"; case 54: return "repeat symbol in tree while there was no value symbol yet"; /*jumped past tree while generating huffman tree, this could be when the tree will have more leaves than symbols after generating it out of the given lenghts. They call this an oversubscribed dynamic bit lengths tree in zlib.*/ case 55: return "jumped past tree while generating huffman tree"; case 56: return "given output image colortype or bitdepth not supported for color conversion"; case 57: return "invalid CRC encountered (checking CRC can be disabled)"; case 58: return "invalid ADLER32 encountered (checking ADLER32 can be disabled)"; case 59: return "requested color conversion not supported"; case 60: return "invalid window size given in the settings of the encoder (must be 0-32768)"; case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ case 62: return "conversion from color to greyscale not supported"; case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; case 67: return "the length of a text chunk keyword given to the encoder is smaller than the minimum of 1 byte"; case 68: return "tried to encode a PLTE chunk with a palette that has less than 1 or more than 256 colors"; case 69: return "unknown chunk type with 'critical' flag encountered by the decoder"; case 71: return "unexisting interlace mode given to encoder (must be 0 or 1)"; case 72: return "while decoding, unexisting compression method encountering in zTXt or iTXt chunk (it must be 0)"; case 73: return "invalid tIME chunk size"; case 74: return "invalid pHYs chunk size"; /*length could be wrong, or data chopped off*/ case 75: return "no null termination char found while decoding text chunk"; case 76: return "iTXt chunk too short to contain required bytes"; case 77: return "integer overflow in buffer size"; case 78: return "failed to open file for reading"; /*file doesn't exist or couldn't be opened for reading*/ case 79: return "failed to open file for writing"; case 80: return "tried creating a tree of 0 symbols"; case 81: return "lazy matching at pos 0 is impossible"; case 82: return "color conversion to palette requested while a color isn't in palette, or index out of bounds"; case 83: return "memory allocation failed"; case 84: return "given image too small to contain all pixels to be encoded"; case 86: return "impossible offset in lz77 encoding (internal bug)"; case 87: return "must provide custom zlib function pointer if LODEPNG_COMPILE_ZLIB is not defined"; case 88: return "invalid filter strategy given for LodePNGEncoderSettings.filter_strategy"; case 89: return "text chunk keyword too short or long: must have size 1-79"; /*the windowsize in the LodePNGCompressSettings. Requiring POT(==> & instead of %) makes encoding 12% faster.*/ case 90: return "windowsize must be a power of two"; case 91: return "invalid decompressed idat size"; case 92: return "integer overflow due to too many pixels"; case 93: return "zero width or height is invalid"; case 94: return "header chunk must have a size of 13 bytes"; case 95: return "integer overflow with combined idat chunk size"; case 96: return "invalid gAMA chunk size"; case 97: return "invalid cHRM chunk size"; case 98: return "invalid sRGB chunk size"; case 99: return "invalid sRGB rendering intent"; case 100: return "invalid ICC profile color type, the PNG specification only allows RGB or GRAY"; case 101: return "PNG specification does not allow RGB ICC profile on grey color types and vice versa"; case 102: return "not allowed to set greyscale ICC profile with colored pixels by PNG specification"; case 103: return "Invalid palette index in bKGD chunk. Maybe it came before PLTE chunk?"; case 104: return "Invalid bKGD color while encoding (e.g. palette index out of range)"; } return "unknown error code"; } #endif /*LODEPNG_COMPILE_ERROR_TEXT*/ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ /* // C++ Wrapper // */ /* ////////////////////////////////////////////////////////////////////////// */ /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_CPP namespace lodepng { #ifdef LODEPNG_COMPILE_DISK unsigned load_file(std::vector& buffer, const std::string& filename) { long size = lodepng_filesize(filename.c_str()); if (size < 0) return 78; buffer.resize((size_t)size); return size == 0 ? 0 : lodepng_buffer_file(&buffer[0], (size_t)size, filename.c_str()); } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ unsigned save_file(const std::vector& buffer, const std::string& filename) { return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); } #endif /* LODEPNG_COMPILE_DISK */ #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_DECODER unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, const LodePNGDecompressSettings& settings) { unsigned char* buffer = 0; size_t buffersize = 0; unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); if (buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } return error; } unsigned decompress(std::vector& out, const std::vector& in, const LodePNGDecompressSettings& settings) { return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER unsigned compress(std::vector& out, const unsigned char* in, size_t insize, const LodePNGCompressSettings& settings) { unsigned char* buffer = 0; size_t buffersize = 0; unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); if (buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } return error; } unsigned compress(std::vector& out, const std::vector& in, const LodePNGCompressSettings& settings) { return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_ZLIB */ #ifdef LODEPNG_COMPILE_PNG State::State() { lodepng_state_init(this); } State::State(const State& other) { lodepng_state_init(this); lodepng_state_copy(this, &other); } State::~State() { lodepng_state_cleanup(this); } State& State::operator=(const State& other) { lodepng_state_copy(this, &other); return *this; } #ifdef LODEPNG_COMPILE_DECODER unsigned decode(std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, size_t insize, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); if (buffer && !error) { State state; state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } return error; } unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) { return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); } unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const unsigned char* in, size_t insize) { unsigned char* buffer = NULL; unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); if (buffer && !error) { size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); out.insert(out.end(), &buffer[0], &buffer[buffersize]); } lodepng_free(buffer); return error; } unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, const std::vector& in) { return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); } #ifdef LODEPNG_COMPILE_DISK unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, LodePNGColorType colortype, unsigned bitdepth) { std::vector buffer; unsigned error = load_file(buffer, filename); if (error) return error; return decode(out, w, h, buffer, colortype, bitdepth); } #endif /* LODEPNG_COMPILE_DECODER */ #endif /* LODEPNG_COMPILE_DISK */ #ifdef LODEPNG_COMPILE_ENCODER unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); if (buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } return error; } unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { if (lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, State& state) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); if (buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } return error; } unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, State& state) { if (lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; return encode(out, in.empty() ? 0 : &in[0], w, h, state); } #ifdef LODEPNG_COMPILE_DISK unsigned encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { std::vector buffer; unsigned error = encode(buffer, in, w, h, colortype, bitdepth); if (!error) error = save_file(buffer, filename); return error; } unsigned encode(const std::string& filename, const std::vector& in, unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { if (lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } #endif /* LODEPNG_COMPILE_DISK */ #endif /* LODEPNG_COMPILE_ENCODER */ #endif /* LODEPNG_COMPILE_PNG */ } /* namespace lodepng */ #endif /*LODEPNG_COMPILE_CPP*/ ================================================ FILE: PinBox/PinBox/source/main.cpp ================================================ //=============================================================================== // enable this for debug log console on top //=============================================================================== //define __CONSOLE_DEBUGING__ //=============================================================================== #include <3ds.h> #include #include #include #include #include #include "ConfigManager.h" #include "PPGraphics.h" #include "PPSessionManager.h" #include "PPUI.h" #include "PPAudio.h" #include "constant.h" void initDbgConsole() { #ifdef CONSOLE_DEBUG consoleInit(GFX_TOP, NULL); printf("Console log initialized\n"); #endif } static u32 *SOC_buffer = NULL; int main() { //--------------------------------------------- // Init svc //--------------------------------------------- acInit(); aptInit(); irrstInit(); Result rc = romfsInit(); if (rc) printf("romfsInit: %08lX\n", rc); else printf("romfs Init Successful!\n"); APT_SetAppCpuTimeLimit(80); //--------------------------------------------- // Init Graphics //--------------------------------------------- PPGraphics::Get()->GraphicsInit(); PPAudio::Get()->AudioInit(); initDbgConsole(); PPUI::InitResource(); //--------------------------------------------- // Init SOCKET //--------------------------------------------- SOC_buffer = (u32*)memalign(SOC_ALIGN, SOC_BUFFERSIZE); u32 ret = socInit(SOC_buffer, SOC_BUFFERSIZE); if (ret != 0) { return 0; } //--------------------------------------------- // Init config //--------------------------------------------- ConfigManager::Get()->InitConfig(); //--------------------------------------------- // Init session manager //--------------------------------------------- PPSessionManager* sm = new PPSessionManager(); //--------------------------------------------- // Wifi Check //--------------------------------------------- u32 wifiStatus = 0; #ifndef USE_CITRA while (aptMainLoop()) { ACU_GetWifiStatus(&wifiStatus); if (wifiStatus) break; //--------------------------------------------- // Update Input //--------------------------------------------- hidScanInput(); irrstScanInput(); PPUI::UpdateInput(); //--------------------------------------------- // Draw UI //--------------------------------------------- PPGraphics::Get()->BeginRender(); PPGraphics::Get()->RenderOn(GFX_BOTTOM); int ret = PPUI::DrawBtmServerSelectScreen(sm); PPGraphics::Get()->EndRender(); if (ret == -1) break; } #else wifiStatus = 1; #endif //--------------------------------------------- // wifiStatus = 0 : not connected to internet // wifiStatus = 1 : Old 3DS internet // wifiStatus = 2 : New 3DS internet //--------------------------------------------- if (wifiStatus) { osSetSpeedupEnable(1); //--------------------------------------------- // Main loop //--------------------------------------------- while (aptMainLoop()) { hidScanInput(); irrstScanInput(); //--------------------------------------------- // Update Input //--------------------------------------------- PPUI::UpdateInput(); sm->UpdateInputStream(PPUI::getKeyHold(), PPUI::getKeyUp(), PPUI::getLeftCircle().dx, PPUI::getLeftCircle().dy, PPUI::getRightCircle().dx, PPUI::getRightCircle().dy); //--------------------------------------------- // Update Frame //--------------------------------------------- PPGraphics::Get()->BeginRender(); //--------------------------------------------- // Draw top UI //--------------------------------------------- #ifndef CONSOLE_DEBUG PPGraphics::Get()->RenderOn(GFX_TOP); if(sm->GetSessionState() == 2) { PPGraphics::Get()->DrawTopScreenSprite(); }else { PPUI::DrawIdleTopScreen(sm); } #endif //--------------------------------------------- // Draw bottom UI //--------------------------------------------- PPGraphics::Get()->RenderOn(GFX_BOTTOM); int r = 0; if (PPUI::HasPopup()) r = PPUI::GetPopup()(); else { switch (sm->GetSessionState()) { case SS_NOT_CONNECTED: case SS_CONNECTING: case SS_CONNECTED: case SS_FAILED: r = PPUI::DrawBtmServerSelectScreen(sm); break; case SS_PAIRED: case SS_STREAMING: r = PPUI::DrawBtmPairedScreen(sm); break; default: break; } } PPGraphics::Get()->EndRender(); if (r == -1) { break; } } } delete sm; PPUI::CleanupResource(); PPGraphics::Get()->GraphicExit(); PPAudio::Get()->AudioExit(); ConfigManager::Get()->Destroy(); irrstExit(); socExit(); free(SOC_buffer); romfsExit(); aptExit(); acExit(); return 0; } ================================================ FILE: PinBox/PinBox/source/vshader.v.pica ================================================ ; Uniforms .fvec projection[4] ; Constants .constf RGBA8_TO_FLOAT4(0.00392156862, 0, 0, 0) .constf ONES(1.0, 1.0, 1.0, 1.0) ; Outputs .out outpos position .out outtc0 texcoord0 .out outclr color ; Inputs (defined as aliases for convenience) .alias inpos v0 .alias inarg v1 .proc main ; outpos = projection * in.pos dp4 outpos.x, projection[0], inpos dp4 outpos.y, projection[1], inpos dp4 outpos.z, projection[2], inpos dp4 outpos.w, projection[3], inpos ; outtc0 = in.texcoord mov outtc0, inarg ; outclr = RGBA8_TO_FLOAT4(in.color) mul outclr, RGBA8_TO_FLOAT4.xxxx, inarg end .end ================================================ FILE: PinBox/PinBox/source/yuv_rgb.c ================================================ // Copyright 2016 Adrien Descamps // Distributed under BSD 3-Clause License #include "yuv_rgb.h" //#include #include uint8_t clamp(int16_t value) { return value<0 ? 0 : (value>255 ? 255 : value); } // Definitions // // E'R, E'G, E'B, E'Y, E'Cb and E'Cr refer to the analog signals // E'R, E'G, E'B and E'Y range is [0:1], while E'Cb and E'Cr range is [-0.5:0.5] // R, G, B, Y, Cb and Cr refer to the digitalized values // The digitalized values can use their full range ([0:255] for 8bit values), // or a subrange (typically [16:235] for Y and [16:240] for CbCr). // We assume here that RGB range is always [0:255], since it is the case for // most digitalized images. // For 8bit values : // * Y = round((YMax-YMin)*E'Y + YMin) // * Cb = round((CbRange)*E'Cb + 128) // * Cr = round((CrRange)*E'Cr + 128) // Where *Min and *Max are the range of each channel // // In the analog domain , the RGB to YCbCr transformation is defined as: // * E'Y = Rf*E'R + Gf*E'G + Bf*E'B // Where Rf, Gf and Bf are constants defined in each standard, with // Rf + Gf + Bf = 1 (necessary to ensure that E'Y range is [0:1]) // * E'Cb = (E'B - E'Y) / CbNorm // * E'Cr = (E'R - E'Y) / CrNorm // Where CbNorm and CrNorm are constants, dependent of Rf, Gf, Bf, computed // to normalize to a [-0.5:0.5] range : CbNorm=2*(1-Bf) and CrNorm=2*(1-Rf) // // Algorithms // // Most operations will be made in a fixed point format for speed, using // N bits of precision. In next section the [x] convention is used for // a fixed point rounded value, that is (int being the c type conversion) // * [x] = int(x*(2^N)+0.5) // N can be different for each factor, we simply use the highest value // that will not overflow in 16 bits intermediate variables. //. // For RGB to YCbCr conversion, we start by generating a pseudo Y value // (noted Y') in fixed point format, using the full range for now. // * Y' = ([Rf]*R + [Gf]*G + [Bf]*B)>>N // We can then compute Cb and Cr by // * Cb = ((B - Y')*[CbRange/(255*CbNorm)])>>N + 128 // * Cr = ((R - Y')*[CrRange/(255*CrNorm)])>>N + 128 // And finally, we normalize Y to its digital range // * Y = (Y'*[(YMax-YMin)/255])>>N + YMin // // For YCbCr to RGB conversion, we first compute the full range Y' value : // * Y' = ((Y-YMin)*[255/(YMax-YMin)])>>N // We can then compute B and R values by : // * B = ((Cb-128)*[(255*CbNorm)/CbRange])>>N + Y' // * R = ((Cr-128)*[(255*CrNorm)/CrRange])>>N + Y' // And finally, for G we know that: // * G = (Y' - (Rf*R + Bf*B)) / Gf // From above: // * G = (Y' - Rf * ((Cr-128)*(255*CrNorm)/CrRange + Y') - Bf * ((Cb-128)*(255*CbNorm)/CbRange + Y')) / Gf // Since 1-Rf-Bf=Gf, we can take Y' out of the division by Gf, and we get: // * G = Y' - (Cr-128)*Rf/Gf*(255*CrNorm)/CrRange - (Cb-128)*Bf/Gf*(255*CbNorm)/CbRange // That we can compute, with fixed point arithmetic, by // * G = Y' - ((Cr-128)*[Rf/Gf*(255*CrNorm)/CrRange] + (Cb-128)*[Bf/Gf*(255*CbNorm)/CbRange])>>N // // Note : in ITU-T T.871(JPEG), Y=Y', so that part could be optimized out #define FIXED_POINT_VALUE(value, precision) ((int)(((value)*(1<r_factor*rgb_ptr1[0] + param->g_factor*rgb_ptr1[1] + param->b_factor*rgb_ptr1[2])>>8; u_tmp = rgb_ptr1[2]-y_tmp; v_tmp = rgb_ptr1[0]-y_tmp; y_ptr1[0]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr1[3] + param->g_factor*rgb_ptr1[4] + param->b_factor*rgb_ptr1[5])>>8; u_tmp += rgb_ptr1[5]-y_tmp; v_tmp += rgb_ptr1[3]-y_tmp; y_ptr1[1]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr2[0] + param->g_factor*rgb_ptr2[1] + param->b_factor*rgb_ptr2[2])>>8; u_tmp += rgb_ptr2[2]-y_tmp; v_tmp += rgb_ptr2[0]-y_tmp; y_ptr2[0]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr2[3] + param->g_factor*rgb_ptr2[4] + param->b_factor*rgb_ptr2[5])>>8; u_tmp += rgb_ptr2[5]-y_tmp; v_tmp += rgb_ptr2[3]-y_tmp; y_ptr2[1]=((y_tmp*param->y_factor)>>7) + param->y_offset; u_ptr[0] = (((u_tmp>>2)*param->cb_factor)>>8) + 128; v_ptr[0] = (((v_tmp>>2)*param->cb_factor)>>8) + 128; rgb_ptr1 += 6; rgb_ptr2 += 6; y_ptr1 += 2; y_ptr2 += 2; u_ptr += 1; v_ptr += 1; } } } void yuv420_rgb24_std( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-1); x+=2) { int8_t u_tmp, v_tmp; u_tmp = u_ptr[0]-128; v_tmp = v_ptr[0]-128; //compute Cb Cr color offsets, common to four pixels int16_t b_cb_offset, r_cr_offset, g_cbcr_offset; b_cb_offset = (param->cb_factor*u_tmp)>>6; r_cr_offset = (param->cr_factor*v_tmp)>>6; g_cbcr_offset = (param->g_cb_factor*u_tmp + param->g_cr_factor*v_tmp)>>7; int16_t y_tmp; y_tmp = (param->y_factor*(y_ptr1[0]-param->y_offset))>>7; rgb_ptr1[2] = clamp(y_tmp + r_cr_offset); rgb_ptr1[1] = clamp(y_tmp - g_cbcr_offset); rgb_ptr1[0] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr1[1]-param->y_offset))>>7; rgb_ptr1[5] = clamp(y_tmp + r_cr_offset); rgb_ptr1[4] = clamp(y_tmp - g_cbcr_offset); rgb_ptr1[3] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr2[0]-param->y_offset))>>7; rgb_ptr2[2] = clamp(y_tmp + r_cr_offset); rgb_ptr2[1] = clamp(y_tmp - g_cbcr_offset); rgb_ptr2[0] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr2[1]-param->y_offset))>>7; rgb_ptr2[5] = clamp(y_tmp + r_cr_offset); rgb_ptr2[4] = clamp(y_tmp - g_cbcr_offset); rgb_ptr2[3] = clamp(y_tmp + b_cb_offset); rgb_ptr1 += 6; rgb_ptr2 += 6; y_ptr1 += 2; y_ptr2 += 2; u_ptr += 1; v_ptr += 1; } } } #ifdef __SSE2__ //see rgb.txt #define UNPACK_RGB24_32_STEP(RS1, RS2, RS3, RS4, RS5, RS6, RD1, RD2, RD3, RD4, RD5, RD6) \ RD1 = _mm_unpacklo_epi8(RS1, RS4); \ RD2 = _mm_unpackhi_epi8(RS1, RS4); \ RD3 = _mm_unpacklo_epi8(RS2, RS5); \ RD4 = _mm_unpackhi_epi8(RS2, RS5); \ RD5 = _mm_unpacklo_epi8(RS3, RS6); \ RD6 = _mm_unpackhi_epi8(RS3, RS6); #define RGB2YUV_16(R, G, B, Y, U, V) \ Y = _mm_add_epi16(_mm_mullo_epi16(R, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(G, _mm_set1_epi16(param->g_factor))); \ Y = _mm_add_epi16(Y, _mm_mullo_epi16(B, _mm_set1_epi16(param->b_factor))); \ Y = _mm_srli_epi16(Y, 8); \ U = _mm_mullo_epi16(_mm_sub_epi16(B, Y), _mm_set1_epi16(param->cb_factor)); \ U = _mm_add_epi16(_mm_srai_epi16(U, 8), _mm_set1_epi16(128)); \ V = _mm_mullo_epi16(_mm_sub_epi16(R, Y), _mm_set1_epi16(param->cr_factor)); \ V = _mm_add_epi16(_mm_srai_epi16(V, 8), _mm_set1_epi16(128)); \ Y = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(Y, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); #define RGB2YUV_32 \ __m128i r_16, g_16, b_16; \ __m128i y1_16, y2_16, cb1_16, cb2_16, cr1_16, cr2_16, Y, cb, cr; \ __m128i tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; \ __m128i rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1)), \ rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+16)), \ rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+32)), \ rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2)), \ rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+16)), \ rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+32)); \ /* unpack rgb24 data to r, g and b data in separate channels*/ \ /* see rgb.txt to get an idea of the algorithm, note that we only go to the next to last step*/ \ /* here, because averaging in horizontal direction is easier like this*/ \ /* The last step is applied further on the Y channel only*/ \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ /* first compute Y', (B-Y') and (R-Y'), in 16bits values, for the first line */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are saved*/ \ r_16 = _mm_unpacklo_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb1_16 = _mm_sub_epi16(b_16, y1_16); \ cr1_16 = _mm_sub_epi16(r_16, y1_16); \ r_16 = _mm_unpacklo_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y2_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr1), Y); \ /* same for the second line, compute Y', (B-Y') and (R-Y'), in 16bits values */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are added to the previous values*/ \ r_16 = _mm_unpackhi_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y1_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y1_16)); \ r_16 = _mm_unpackhi_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y2_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr2), Y); \ /* Rescale Cb and Cr to their final range */ \ cb1_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cb1_16, 2), _mm_set1_epi16(param->cb_factor)), 8), _mm_set1_epi16(128)); \ cr1_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cr1_16, 2), _mm_set1_epi16(param->cr_factor)), 8), _mm_set1_epi16(128)); \ \ /* do the same again with next data */ \ rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1+48)), \ rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+64)), \ rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+80)), \ rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2+48)), \ rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+64)), \ rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+80)); \ /* unpack rgb24 data to r, g and b data in separate channels*/ \ /* see rgb.txt to get an idea of the algorithm, note that we only go to the next to last step*/ \ /* here, because averaging in horizontal direction is easier like this*/ \ /* The last step is applied further on the Y channel only*/ \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ /* first compute Y', (B-Y') and (R-Y'), in 16bits values, for the first line */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are saved*/ \ r_16 = _mm_unpacklo_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb2_16 = _mm_sub_epi16(b_16, y1_16); \ cr2_16 = _mm_sub_epi16(r_16, y1_16); \ r_16 = _mm_unpacklo_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y2_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr1+16), Y); \ /* same for the second line, compute Y', (B-Y') and (R-Y'), in 16bits values */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are added to the previous values*/ \ r_16 = _mm_unpackhi_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y1_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y1_16)); \ r_16 = _mm_unpackhi_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y2_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr2+16), Y); \ /* Rescale Cb and Cr to their final range */ \ cb2_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cb2_16, 2), _mm_set1_epi16(param->cb_factor)), 8), _mm_set1_epi16(128)); \ cr2_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cr2_16, 2), _mm_set1_epi16(param->cr_factor)), 8), _mm_set1_epi16(128)); \ /* Pack and save Cb Cr */ \ cb = _mm_packus_epi16(cb1_16, cb2_16); \ cr = _mm_packus_epi16(cr1_16, cr2_16); \ SAVE_SI128((__m128i*)(u_ptr), cb); \ SAVE_SI128((__m128i*)(v_ptr), cr); void rgb24_yuv420_sse(uint32_t width, uint32_t height, const uint8_t *RGB, uint32_t RGB_stride, uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_load_si128 #define SAVE_SI128 _mm_stream_si128 const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; for(x=0; x<(width-31); x+=32) { RGB2YUV_32 rgb_ptr1+=96; rgb_ptr2+=96; y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; } } #undef LOAD_SI128 #undef SAVE_SI128 } void rgb24_yuv420_sseu(uint32_t width, uint32_t height, const uint8_t *RGB, uint32_t RGB_stride, uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_loadu_si128 #define SAVE_SI128 _mm_storeu_si128 const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; for(x=0; x<(width-31); x+=32) { RGB2YUV_32 rgb_ptr1+=96; rgb_ptr2+=96; y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; } } #undef LOAD_SI128 #undef SAVE_SI128 } #endif #ifdef __SSE2__ #define UV2RGB_16(U,V,R1,G1,B1,R2,G2,B2) \ r_tmp = _mm_srai_epi16(_mm_mullo_epi16(V, _mm_set1_epi16(param->cr_factor)), 6); \ g_tmp = _mm_srai_epi16(_mm_add_epi16( \ _mm_mullo_epi16(U, _mm_set1_epi16(param->g_cb_factor)), \ _mm_mullo_epi16(V, _mm_set1_epi16(param->g_cr_factor))), 7); \ b_tmp = _mm_srai_epi16(_mm_mullo_epi16(U, _mm_set1_epi16(param->cb_factor)), 6); \ R1 = _mm_unpacklo_epi16(r_tmp, r_tmp); \ G1 = _mm_unpacklo_epi16(g_tmp, g_tmp); \ B1 = _mm_unpacklo_epi16(b_tmp, b_tmp); \ R2 = _mm_unpackhi_epi16(r_tmp, r_tmp); \ G2 = _mm_unpackhi_epi16(g_tmp, g_tmp); \ B2 = _mm_unpackhi_epi16(b_tmp, b_tmp); \ #define ADD_Y2RGB_16(Y1,Y2,R1,G1,B1,R2,G2,B2) \ Y1 = _mm_srai_epi16(_mm_mullo_epi16(Y1, _mm_set1_epi16(param->y_factor)), 7); \ Y2 = _mm_srai_epi16(_mm_mullo_epi16(Y2, _mm_set1_epi16(param->y_factor)), 7); \ \ R1 = _mm_add_epi16(Y1, R1); \ G1 = _mm_sub_epi16(Y1, G1); \ B1 = _mm_add_epi16(Y1, B1); \ R2 = _mm_add_epi16(Y2, R2); \ G2 = _mm_sub_epi16(Y2, G2); \ B2 = _mm_add_epi16(Y2, B2); \ #define PACK_RGB24_32_STEP(RS1, RS2, RS3, RS4, RS5, RS6, RD1, RD2, RD3, RD4, RD5, RD6) \ RD1 = _mm_packus_epi16(_mm_and_si128(RS1,_mm_set1_epi16(0xFF)), _mm_and_si128(RS2,_mm_set1_epi16(0xFF))); \ RD2 = _mm_packus_epi16(_mm_and_si128(RS3,_mm_set1_epi16(0xFF)), _mm_and_si128(RS4,_mm_set1_epi16(0xFF))); \ RD3 = _mm_packus_epi16(_mm_and_si128(RS5,_mm_set1_epi16(0xFF)), _mm_and_si128(RS6,_mm_set1_epi16(0xFF))); \ RD4 = _mm_packus_epi16(_mm_srli_epi16(RS1,8), _mm_srli_epi16(RS2,8)); \ RD5 = _mm_packus_epi16(_mm_srli_epi16(RS3,8), _mm_srli_epi16(RS4,8)); \ RD6 = _mm_packus_epi16(_mm_srli_epi16(RS5,8), _mm_srli_epi16(RS6,8)); \ #define PACK_RGB24_32(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ #define YUV2RGB_32 \ __m128i r_tmp, g_tmp, b_tmp; \ __m128i r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2; \ __m128i r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2; \ __m128i y_16_1, y_16_2; \ \ __m128i u = LOAD_SI128((const __m128i*)(u_ptr)); \ __m128i v = LOAD_SI128((const __m128i*)(v_ptr)); \ u = _mm_add_epi8(u, _mm_set1_epi8(-128)); \ v = _mm_add_epi8(v, _mm_set1_epi8(-128)); \ \ /* process first 16 pixels of first line */\ __m128i u_16 = _mm_srai_epi16(_mm_unpacklo_epi8(u, u), 8); \ __m128i v_16 = _mm_srai_epi16(_mm_unpacklo_epi8(v, v), 8); \ \ UV2RGB_16(u_16, v_16, r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2) \ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ __m128i y = LOAD_SI128((const __m128i*)(y_ptr1)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_11 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_11 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_11 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process first 16 pixels of second line */\ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr2)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_21 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_21 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_21 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process last 16 pixels of first line */\ u_16 = _mm_srai_epi16(_mm_unpackhi_epi8(u, u), 8); \ v_16 = _mm_srai_epi16(_mm_unpackhi_epi8(v, v), 8); \ \ UV2RGB_16(u_16, v_16, r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2) \ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr1+16)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_12 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_12 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_12 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process last 16 pixels of second line */\ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr2+16)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_22 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_22 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_22 = _mm_packus_epi16(b_16_1, b_16_2); \ \ __m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6; \ \ PACK_RGB24_32(r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6) \ SAVE_SI128((__m128i*)(rgb_ptr1), rgb_1); \ SAVE_SI128((__m128i*)(rgb_ptr1+16), rgb_2); \ SAVE_SI128((__m128i*)(rgb_ptr1+32), rgb_3); \ SAVE_SI128((__m128i*)(rgb_ptr1+48), rgb_4); \ SAVE_SI128((__m128i*)(rgb_ptr1+64), rgb_5); \ SAVE_SI128((__m128i*)(rgb_ptr1+80), rgb_6); \ \ PACK_RGB24_32(r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6) \ SAVE_SI128((__m128i*)(rgb_ptr2), rgb_1); \ SAVE_SI128((__m128i*)(rgb_ptr2+16), rgb_2); \ SAVE_SI128((__m128i*)(rgb_ptr2+32), rgb_3); \ SAVE_SI128((__m128i*)(rgb_ptr2+48), rgb_4); \ SAVE_SI128((__m128i*)(rgb_ptr2+64), rgb_5); \ SAVE_SI128((__m128i*)(rgb_ptr2+80), rgb_6); \ void yuv420_rgb24_sse( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_load_si128 #define SAVE_SI128 _mm_stream_si128 const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-31); x+=32) { YUV2RGB_32 y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; rgb_ptr1+=96; rgb_ptr2+=96; } } #undef LOAD_SI128 #undef SAVE_SI128 } void yuv420_rgb24_sseu( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_loadu_si128 #define SAVE_SI128 _mm_storeu_si128 const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-31); x+=32) { YUV2RGB_32 y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; rgb_ptr1+=96; rgb_ptr2+=96; } } #undef LOAD_SI128 #undef SAVE_SI128 } #endif //__SSE2__ ================================================ FILE: PinBox/PinBox/tools/citra/README.md ================================================ **BEFORE FILING AN ISSUE, READ THE RELEVANT SECTION IN THE [CONTRIBUTING](https://github.com/citra-emu/citra/blob/master/CONTRIBUTING.md#reporting-issues) FILE!!!** Citra ============== [![Travis CI Build Status](https://travis-ci.org/citra-emu/citra.svg?branch=master)](https://travis-ci.org/citra-emu/citra) [![AppVeyor CI Build Status](https://ci.appveyor.com/api/projects/status/sdf1o4kh3g1e68m9?svg=true)](https://ci.appveyor.com/project/bunnei/citra) Citra is an experimental open-source Nintendo 3DS emulator/debugger written in C++. It is written with portability in mind, with builds actively maintained for Windows, Linux and macOS. Citra emulates a subset of 3DS hardware and therefore is useful for running/debugging homebrew applications, and it is also able to run many commercial games! Some of these do not run at a playable state, but we are working every day to advance the project forward. (Playable here means compatibility of at least "Okay" on our [game compatibility list](https://citra-emu.org/game).) Citra is licensed under the GPLv2 (or any later version). Refer to the license.txt file included. Please read the [FAQ](https://citra-emu.org/wiki/faq/) before getting started with the project. Check out our [website](https://citra-emu.org/)! For development discussion, please join us at #citra-dev on freenode. ### Development Most of the development happens on GitHub. It's also where [our central repository](https://github.com/citra-emu/citra) is hosted. If you want to contribute please take a look at the [Contributor's Guide](CONTRIBUTING.md) and [Developer Information](https://github.com/citra-emu/citra/wiki/Developer-Information). You should as well contact any of the developers in the forum in order to know about the current state of the emulator because the [TODO list](https://docs.google.com/document/d/1SWIop0uBI9IW8VGg97TAtoT_CHNoP42FzYmvG1F4QDA) isn't maintained anymore. If you want to contribute to the user interface translation, please checkout [citra project on transifex](https://www.transifex.com/citra/citra). We centralize the translation work there, and periodically upstream translation. ### Building * __Windows__: [Windows Build](https://github.com/citra-emu/citra/wiki/Building-For-Windows) * __Linux__: [Linux Build](https://github.com/citra-emu/citra/wiki/Building-For-Linux) * __macOS__: [macOS Build](https://github.com/citra-emu/citra/wiki/Building-for-macOS) ### Support We happily accept monetary donations or donated games and hardware. Please see our [donations page](https://citra-emu.org/donate/) for more information on how you can contribute to Citra. Any donations received will go towards things like: * 3DS consoles for developers to explore the hardware * 3DS games for testing * Any equipment required for homebrew * Infrastructure setup * Eventually 3D displays to get proper 3D output working We also more than gladly accept used 3DS consoles, preferably ones with firmware 4.5 or lower! If you would like to give yours away, don't hesitate to join our IRC channel #citra on [Freenode](http://webchat.freenode.net/?channels=citra) and talk to neobrain or bunnei. Mind you, IRC is slow-paced, so it might be a while until people reply. If you're in a hurry you can just leave contact details in the channel or via private message and we'll get back to you. ================================================ FILE: PinBox/PinBox/tools/citra/license.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. The icons used in this project have the following licenses: Icon Name | License | Origin/Author --- | --- | --- checked.png | Free for non-commercial use connected.png | CC BY-ND 3.0 | https://icons8.com disconnected.png | CC BY-ND 3.0 | https://icons8.com failed.png | Free for non-commercial use lock.png | CC BY-ND 3.0 | https://icons8.com plus_folder.png | CC BY-ND 3.0 | https://icons8.com bad_folder.png | CC BY-ND 3.0 | https://icons8.com chip.png | CC BY-ND 3.0 | https://icons8.com folder.png | CC BY-ND 3.0 | https://icons8.com plus.png | CC BY-ND 3.0 | https://icons8.com sd_card.png | CC BY-ND 3.0 | https://icons8.com ================================================ FILE: PinBox/PinBox.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PinBox", "PinBox\PinBox.vcxproj", "{7C85BF63-9A1F-43F0-9560-6E51BA537C01}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Citra|x64 = Citra|x64 Citra|x86 = Citra|x86 Citra-QT|x64 = Citra-QT|x64 Citra-QT|x86 = Citra-QT|x86 Netlink|x64 = Netlink|x64 Netlink|x86 = Netlink|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra|x64.ActiveCfg = Citra|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra|x64.Build.0 = Citra|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra|x86.ActiveCfg = Citra|Win32 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra|x86.Build.0 = Citra|Win32 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra-QT|x64.ActiveCfg = Citra-QT|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra-QT|x64.Build.0 = Citra-QT|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra-QT|x86.ActiveCfg = Citra-QT|Win32 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Citra-QT|x86.Build.0 = Citra-QT|Win32 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Netlink|x64.ActiveCfg = Netlink|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Netlink|x64.Build.0 = Netlink|x64 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Netlink|x86.ActiveCfg = Netlink|Win32 {7C85BF63-9A1F-43F0-9560-6E51BA537C01}.Netlink|x86.Build.0 = Netlink|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: PinBoxServer/Check-Pinbox-Firewall-Rules.bat ================================================ @echo off title = Pinbox Firewall Setup echo Checking PinBox Server executable... IF NOT EXIST %~dp0PinBoxServer.exe GOTO pinnotdetected echo PinBox Executable found! echo Elevating privilegies... if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b) echo Admin detected. echo Adding rules... rem REMEMBER TO CHANGE THE PROGRAM NAME IF THE BINARY FILE NAME CHANGES netsh advfirewall firewall add rule name="PinboxOut" dir=out action=allow profile=any program= "%~dp0PinBoxServer.exe" enable=yes netsh advfirewall firewall add rule name="PinBoxIn" dir=in action=allow profile=any program= "%~dp0PinBoxServer.exe" enable=yes echo Done pause exit :pinnotdetected echo PinBoxServer.exe doesn't exists. Remember to run this script in THE SAME FOLDER AS THE EXECUTABLE. pause exit ================================================ FILE: PinBoxServer/PinBoxServer/AudioStreamSession.cpp ================================================ #include "stdafx.h" #include "AudioStreamSession.h" #include #include #include "const.h" #define AUDIO_BUFFER_SIZE 0x500000 // 5 Mb namespace { void createNew(void* arg) { static_cast(arg)->loopbackThread(); } } void AudioStreamSession::useDefaultDevice() { HRESULT hr = S_OK; IMMDeviceEnumerator *pMMDeviceEnumerator; //------------------------------------------------ // activate a device enumerator hr = CoCreateInstance( __uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pMMDeviceEnumerator ); if (FAILED(hr)) { printf("CoCreateInstance(IMMDeviceEnumerator) failed: hr = 0x%08x", hr); return; } //------------------------------------------------ // get the default render endpoint hr = pMMDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &_pMMDevice); if (FAILED(hr)) { printf("IMMDeviceEnumerator::GetDefaultAudioEndpoint failed: hr = 0x%08x", hr); } pMMDeviceEnumerator->Release(); } void AudioStreamSession::StartAudioStream() { CoInitialize(NULL); this->useDefaultDevice(); //----------------------------------------------------- // create a "stop capturing now" event _stopEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (NULL == _stopEvent) { printf("CreateEvent failed: last error is %u", GetLastError()); return; } //----------------------------------------------------- // init tmp buffer audioBuffer = (u8*)malloc(AUDIO_BUFFER_SIZE); audioBufferSize = 0; audioFrames = 0; _mutex = new std::mutex(); //----------------------------------------------------- // start loopback record thread _thread = std::thread(createNew, static_cast(this)); } void AudioStreamSession::StopStreaming() { SetEvent(_stopEvent); } void AudioStreamSession::ReadFromBuffer(u8* outBuf, u32 readSize) { if (!outBuf) return; if (readSize > audioBufferSize) return; _mutex->lock(); // read memory to buf memcpy(outBuf, audioBuffer, readSize); // update pointer cursor audioBufferSize -= readSize; // shift memory back to place memcpy(audioBuffer, audioBuffer + readSize, audioBufferSize); _mutex->unlock(); } void AudioStreamSession::ResetStorageBuffer() { _mutex->lock(); audioBufferSize = 0; _mutex->unlock(); } void AudioStreamSession::Pause() { if (_isPaused) return; _isPaused = true; HRESULT hr = S_OK; hr = _pAudioClient->Stop(); if (FAILED(hr)) { printf("IAudioClient::Stop failed: hr = 0x%08x\n", hr); return; } } void AudioStreamSession::Resume() { if (!_isPaused) return; _isPaused = false; HRESULT hr = S_OK; hr = _pAudioClient->Start(); if (FAILED(hr)) { printf("IAudioClient::Start failed: hr = 0x%08x\n", hr); return; } } void AudioStreamSession::loopbackThread() { HRESULT hr = S_OK; hr = _pMMDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&_pAudioClient); if (FAILED(hr)) { printf("IMMDevice::Activate(IAudioClient) failed: hr = 0x%08x\n", hr); return; } // get the default device periodicity REFERENCE_TIME hnsDefaultDevicePeriod; hr = _pAudioClient->GetDevicePeriod(&hnsDefaultDevicePeriod, NULL); if (FAILED(hr)) { printf("IAudioClient::GetDevicePeriod failed: hr = 0x%08x\n", hr); return; } // get the default device format WAVEFORMATEX *pwfx; hr = _pAudioClient->GetMixFormat(&pwfx); if (FAILED(hr)) { printf("IAudioClient::GetMixFormat failed: hr = 0x%08x\n", hr); return; } //pwfx->nSamplesPerSec = 22050; switch (pwfx->wFormatTag) { case WAVE_FORMAT_IEEE_FLOAT: pwfx->wFormatTag = WAVE_FORMAT_PCM; pwfx->wBitsPerSample = 16; pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec; break; case WAVE_FORMAT_EXTENSIBLE: // naked scope for case-local variable PWAVEFORMATEXTENSIBLE pEx = reinterpret_cast(pwfx); if (IsEqualGUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, pEx->SubFormat)) { pEx->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; pEx->Samples.wValidBitsPerSample = 16; pwfx->wBitsPerSample = 16; // 2 bytes per sample pwfx->nBlockAlign = pwfx->nChannels * pwfx->wBitsPerSample / 8; pwfx->nAvgBytesPerSec = pwfx->nBlockAlign * pwfx->nSamplesPerSec; } else { printf("Don't know how to coerce mix format to int-16\n"); return; } break; } pwfx->cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); //pwfx->cbSize = 0; // create a periodic waitable timer HANDLE hWakeUp = CreateWaitableTimer(NULL, FALSE, NULL); UINT32 nBlockAlign = pwfx->nBlockAlign; // call IAudioClient::Initialize // note that AUDCLNT_STREAMFLAGS_LOOPBACK and AUDCLNT_STREAMFLAGS_EVENTCALLBACK // do not work together... // the "data ready" event never gets set // so we're going to do a timer-driven loop hr = _pAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED, // try this ? AUDCLNT_SHAREMODE_EXCLUSIVE AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, pwfx, 0 ); if (FAILED(hr)) { printf(">>>>> Error: IAudioClient::Initialize failed: hr = 0x%08x\n", hr); return; } sampleRate = (u32)pwfx->nSamplesPerSec; // activate an IAudioCaptureClient IAudioCaptureClient *pAudioCaptureClient; hr = _pAudioClient->GetService( __uuidof(IAudioCaptureClient), (void**)&pAudioCaptureClient ); // set the waitable timer LARGE_INTEGER liFirstFire; liFirstFire.QuadPart = -hnsDefaultDevicePeriod / 2; // negative means relative time LONG lTimeBetweenFires = (LONG)hnsDefaultDevicePeriod / 2 / (10 * 1000); // convert to milliseconds BOOL bOK = SetWaitableTimer( hWakeUp, &liFirstFire, lTimeBetweenFires, NULL, NULL, FALSE ); // call IAudioClient::Start hr = _pAudioClient->Start(); if (FAILED(hr)) { printf("IAudioClient::Start failed: hr = 0x%08x\n", hr); return; } // loopback capture loop HANDLE waitArray[2] = { _stopEvent, hWakeUp }; DWORD dwWaitResult; bool bDone = false; for (UINT32 nPasses = 0; !bDone; nPasses++) { // drain data while it is available UINT32 nNextPacketSize; for (hr = pAudioCaptureClient->GetNextPacketSize(&nNextPacketSize); SUCCEEDED(hr) && nNextPacketSize > 0; hr = pAudioCaptureClient->GetNextPacketSize(&nNextPacketSize)) { // get the captured data BYTE *pData; UINT32 nNumFramesToRead; DWORD dwFlags; hr = pAudioCaptureClient->GetBuffer( &pData, &nNumFramesToRead, &dwFlags, NULL, NULL ); if(dwFlags & AUDCLNT_BUFFERFLAGS_SILENT) { pData = NULL; //TODO: send data to write as silent ? continue; } LONG lBytesToWrite = nNumFramesToRead * nBlockAlign; // write audio wave data into tmp buffer to wait for encode _mutex->lock(); audioFrames += nNumFramesToRead; if(audioBufferSize + lBytesToWrite < 5242880) { memcpy(audioBuffer + audioBufferSize, pData, lBytesToWrite); audioBufferSize += lBytesToWrite; } _mutex->unlock(); hr = pAudioCaptureClient->ReleaseBuffer(nNumFramesToRead); } //------------------------------------------------------------------------- // event result if have dwWaitResult = WaitForMultipleObjects( ARRAYSIZE(waitArray), waitArray, FALSE, INFINITE ); if (WAIT_OBJECT_0 == dwWaitResult) { printf("Received stop event after %u passes\n", nPasses); bDone = true; continue; // exits loop } if (WAIT_OBJECT_0 + 1 != dwWaitResult) { printf("Unexpected WaitForMultipleObjects return value %u on pass %u\n", dwWaitResult, nPasses); return; } } printf("Closing audio capture session.\n"); //--------------------------------------- // finish record data // need send something here to end that stream //--------------------------------------- _pAudioClient->Stop(); CancelWaitableTimer(hWakeUp); pAudioCaptureClient->Release(); CloseHandle(hWakeUp); CoTaskMemFree(pwfx); _pAudioClient->Release(); CloseHandle(_stopEvent); CoUninitialize(); _pAudioClient = NULL; free(audioBuffer); if (_pMMDevice != NULL) _pMMDevice->Release(); _pMMDevice = NULL; } ================================================ FILE: PinBoxServer/PinBoxServer/AudioStreamSession.h ================================================ #pragma once #ifndef _AUDIO_STREAM_SESSION_H__ #define _AUDIO_STREAM_SESSION_H__ #include #include #include #include #include "PPMessage.h" #include class AudioStreamSession { private: IAudioClient *_pAudioClient; IMMDevice *_pMMDevice; HANDLE _stopEvent; std::thread _thread; bool _isPaused = false; std::mutex *_mutex; void useDefaultDevice(); public: u32 audioBufferSize = 0; u8* audioBuffer = nullptr; int audioFrames = 0; u32 sampleRate = 0; public: // Start audio stream session ( init every thing relate ) void StartAudioStream(); void Pause(); void Resume(); // Stop audio stream session ( release every thing relate ) void StopStreaming(); // Read input amount of stored audio buffer if available void ReadFromBuffer(u8* outBuf, u32 readSize); // Reset storage buffer to zero ( in case of user want to avoid read old data to avoid laggy ) void ResetStorageBuffer(); void loopbackThread(); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/Check-Pinbox-Firewall-Rules.bat ================================================ @echo off title = Pinbox Firewall Setup echo Checking PinBox Server executable... IF NOT EXIST %~dp0PinBoxServer.exe GOTO pinnotdetected echo PinBox Executable found! echo Elevating privilegies... if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b) echo Admin detected. echo Adding rules... rem REMEMBER TO CHANGE THE PROGRAM NAME IF THE BINARY FILE NAME CHANGES netsh advfirewall firewall add rule name="PinboxOut" dir=out action=allow profile=any program= "%~dp0PinBoxServer.exe" enable=yes netsh advfirewall firewall add rule name="PinBoxIn" dir=in action=allow profile=any program= "%~dp0PinBoxServer.exe" enable=yes echo Done pause exit :pinnotdetected echo PinBoxServer.exe doesn't exists. Remember to run this script in THE SAME FOLDER AS THE EXECUTABLE. pause exit ================================================ FILE: PinBoxServer/PinBoxServer/HubItem.h ================================================ #ifndef _PP_HUB_TITEM_H_ #define _PP_HUB_TITEM_H_ #include "PPMessage.h" enum HubItemType { HUB_SCREEN = 0x0, HUB_APP, HUB_MOVIE, }; class HubItem { public: std::string uuid; // app name std::string name; // thumb image should be 64x64 png image u8* thumbBuf; u32 thumbSize; HubItemType type; // data std::string thumbImage; std::string exePath; std::string processName; }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/InputStreamSession.cpp ================================================ #include "stdafx.h" #include "InputStreamSession.h" #include #include #include InputStreamSession::InputStreamSession() { initMapKey(); LoadInputConfig(); initVIGEM(); } InputStreamSession::~InputStreamSession() { } void InputStreamSession::LoadInputConfig() { //----------------------------------------------- // Init default mapping //----------------------------------------------- m_defaultProfile = new KeyMappingProfile(); m_defaultProfile->name = "Default"; //m_defaultProfile->type = "keyboard"; m_defaultProfile->type = "x360"; m_defaultProfile->mappings[0] = FakeInput::Key_Z; m_defaultProfile->mappings[1] = FakeInput::Key_X; m_defaultProfile->mappings[10] = FakeInput::Key_A; m_defaultProfile->mappings[11] = FakeInput::Key_S; m_defaultProfile->mappings[9] = FakeInput::Key_Q; m_defaultProfile->mappings[8] = FakeInput::Key_W; m_defaultProfile->mappings[6] = FakeInput::Key_Right; m_defaultProfile->mappings[7] = FakeInput::Key_Down; m_defaultProfile->mappings[5] = FakeInput::Key_Left; m_defaultProfile->mappings[4] = FakeInput::Key_Up; m_defaultProfile->mappings[3] = FakeInput::Key_N; m_defaultProfile->mappings[2] = FakeInput::Key_M; m_defaultProfile->circlePadAsMouse = false; // circle pad act as dpad m_defaultProfile->mappings[30] = FakeInput::Key_Up; m_defaultProfile->mappings[31] = FakeInput::Key_Down; m_defaultProfile->mappings[29] = FakeInput::Key_Left; m_defaultProfile->mappings[28] = FakeInput::Key_Right; // for new3ds only m_defaultProfile->mappings[14] = FakeInput::Key_E; m_defaultProfile->mappings[15] = FakeInput::Key_D; m_keyMappingProfiles[m_defaultProfile->name] = m_defaultProfile; // x360 m_defaultProfile->controller[0] = XUSB_GAMEPAD_A; m_defaultProfile->controller[1] = XUSB_GAMEPAD_B; m_defaultProfile->controller[10] = XUSB_GAMEPAD_X; m_defaultProfile->controller[11] = XUSB_GAMEPAD_Y; m_defaultProfile->controller[9] = XUSB_GAMEPAD_LEFT_SHOULDER; m_defaultProfile->controller[8] = XUSB_GAMEPAD_RIGHT_SHOULDER; m_defaultProfile->controller[6] = XUSB_GAMEPAD_DPAD_UP; m_defaultProfile->controller[7] = XUSB_GAMEPAD_DPAD_DOWN; m_defaultProfile->controller[5] = XUSB_GAMEPAD_DPAD_LEFT; m_defaultProfile->controller[4] = XUSB_GAMEPAD_DPAD_RIGHT; m_defaultProfile->controller[3] = XUSB_GAMEPAD_START; m_defaultProfile->controller[2] = XUSB_GAMEPAD_BACK; //----------------------------------------------- // load config //----------------------------------------------- libconfig::Config inputConfigFile; try { inputConfigFile.readFile("input.cfg"); }catch(const libconfig::FileIOException& fioex) { std::cout << "[Error] Input config file was not found." << std::endl << std::flush; } catch (const libconfig::ParseException& pex) { std::cout << "[Error] Input config file corrupted." << std::endl << std::flush; } // load input profiles const libconfig::Setting& root = inputConfigFile.getRoot(); const libconfig::Setting& inputProfiles = root["input_profiles"]; int profilesCount = inputProfiles.getLength(); for (int i = 0; i < profilesCount; ++i) { KeyMappingProfile* profile = new KeyMappingProfile(); std::string name, type; if(!inputProfiles[i].lookupValue("name", name) && inputProfiles[i].lookupValue("type", type)) { continue; } profile->name = name; profile->type = type; if(type == "keyboard") { std::string btn_A, btn_B, btn_X, btn_Y; std::string btn_DPAD_UP, btn_DPAD_DOWN, btn_DPAD_LEFT, btn_DPAD_RIGHT; std::string btn_L, btn_R, btn_ZL, btn_ZR; std::string btn_START, btn_SELECT; bool circle_as_mouse, zl_zr_as_mouse_btn; if (!inputProfiles[i].lookupValue("btn_A", btn_A) && inputProfiles[i].lookupValue("btn_B", btn_B) && inputProfiles[i].lookupValue("btn_X", btn_X) && inputProfiles[i].lookupValue("btn_Y", btn_Y) && inputProfiles[i].lookupValue("btn_DPAD_UP", btn_DPAD_UP) && inputProfiles[i].lookupValue("btn_DPAD_DOWN", btn_DPAD_DOWN) && inputProfiles[i].lookupValue("btn_DPAD_LEFT", btn_DPAD_LEFT) && inputProfiles[i].lookupValue("btn_DPAD_RIGHT", btn_DPAD_RIGHT) && inputProfiles[i].lookupValue("btn_L", btn_L) && inputProfiles[i].lookupValue("btn_R", btn_R) && inputProfiles[i].lookupValue("btn_START", btn_START) && inputProfiles[i].lookupValue("btn_SELECT", btn_SELECT)) { continue; } profile->mappings[0] = m_keyMapping[btn_A]; profile->mappings[1] = m_keyMapping[btn_B]; profile->mappings[10] = m_keyMapping[btn_X]; profile->mappings[11] = m_keyMapping[btn_Y]; profile->mappings[9] = m_keyMapping[btn_L]; profile->mappings[8] = m_keyMapping[btn_R]; profile->mappings[14] = m_keyMapping[btn_ZL]; profile->mappings[15] = m_keyMapping[btn_ZR]; profile->mappings[6] = m_keyMapping[btn_DPAD_RIGHT]; profile->mappings[7] = m_keyMapping[btn_DPAD_DOWN]; profile->mappings[5] = m_keyMapping[btn_DPAD_LEFT]; profile->mappings[4] = m_keyMapping[btn_DPAD_UP]; profile->mappings[3] = m_keyMapping[btn_START]; profile->mappings[2] = m_keyMapping[btn_SELECT]; // optional // load for zl and zr if (inputProfiles[i].lookupValue("circle_pad_as_mouse", circle_as_mouse)) { inputProfiles[i].lookupValue("zl_zr_as_mouse_button", zl_zr_as_mouse_btn); profile->circlePadAsMouse = circle_as_mouse; profile->ZLRAsMouseButton = zl_zr_as_mouse_btn; } // optional // load for zl and zr if (!zl_zr_as_mouse_btn) { if (inputProfiles[i].lookupValue("btn_ZL", btn_ZL)) profile->mappings[14] = m_keyMapping[btn_ZL]; if (inputProfiles[i].lookupValue("btn_ZR", btn_ZR)) profile->mappings[15] = m_keyMapping[btn_ZR]; } m_keyMappingProfiles[profile->name] = profile; }else if(type == "x360") { profile->controller[0] = XUSB_GAMEPAD_A; profile->controller[1] = XUSB_GAMEPAD_B; profile->controller[10] = XUSB_GAMEPAD_X; profile->controller[11] = XUSB_GAMEPAD_Y; profile->controller[9] = XUSB_GAMEPAD_LEFT_SHOULDER; profile->controller[8] = XUSB_GAMEPAD_RIGHT_SHOULDER; profile->controller[6] = XUSB_GAMEPAD_DPAD_UP; profile->controller[7] = XUSB_GAMEPAD_DPAD_DOWN; profile->controller[5] = XUSB_GAMEPAD_DPAD_LEFT; profile->controller[4] = XUSB_GAMEPAD_DPAD_RIGHT; profile->controller[3] = XUSB_GAMEPAD_START; profile->controller[2] = XUSB_GAMEPAD_BACK; } } } void InputStreamSession::UpdateInput(uint32_t down, uint32_t up, short cx, short cy, short ctx, short cty) { m_OldDown = down; m_OldUp = up; m_OldCX = cx; m_OldCY = cy; m_OldCTX = ctx; m_OldCTY = cty; /*std::cout << "Input Down:" << down << " - Up:" << up << " - CX:" << cx << " - CY:" << cy << " - CTX:" << ctx << " - CTY:" << cty << std::endl << std::flush;*/ ProcessInput(); } void InputStreamSession::ProcessInput() { // validate profile if (m_currentProfile.empty()) m_currentProfile = "Default"; if (m_keyMappingProfiles.find(m_currentProfile) == m_keyMappingProfiles.end()) m_currentProfile = "Default"; KeyMappingProfile *profile = m_keyMappingProfiles[m_currentProfile]; if(profile->type == "keyboard") { // Key Input for (uint8_t i = 0; i < 32; ++i) { if (m_OldDown & BIT(i)) { if (profile->mappings.find(i) != profile->mappings.end()) { FakeInput::Keyboard::pressKey(profile->mappings[i]); } }else { if (profile->mappings.find(i) != profile->mappings.end()) { FakeInput::Keyboard::releaseKey(profile->mappings[i]); } } } if (profile->circlePadAsMouse) { // Circle Pad short _cx = (c_cpadMax - m_OldCX); short _cy = (c_cpadMax - m_OldCY); FakeInput::Mouse::move(_cx, _cy); } }else if(profile->type == "x360") { m_x360Report.wButtons = 0; m_x360Report.bLeftTrigger = 0; m_x360Report.bRightTrigger = 0; // Key Input for (uint8_t i = 0; i < 32; ++i) { if (m_OldDown & BIT(i)) { if (profile->controller.find(i) != profile->controller.end()) { m_x360Report.wButtons |= profile->controller[i]; } } } // ZL if (m_OldDown & BIT(14)) { m_x360Report.bLeftTrigger = 250; } if(m_OldUp & BIT(14)) { m_x360Report.bLeftTrigger = 0; } // ZR if (m_OldDown & BIT(15)) { m_x360Report.bRightTrigger = 250; } if (m_OldUp & BIT(15)) { m_x360Report.bRightTrigger = 0; } const short MAX_STICK_RANGE = 30000; const float ADDITION_CSTICK = 0.2f; // Left stick if (m_OldCX > 0 && m_OldCX <= c_cpadDeadZone) m_OldCX = 0; if (m_OldCX < 0 && m_OldCX >= -c_cpadDeadZone) m_OldCX = 0; if (m_OldCY > 0 && m_OldCY <= c_cpadDeadZone) m_OldCY = 0; if (m_OldCY < 0 && m_OldCY >= -c_cpadDeadZone) m_OldCY = 0; float pCx = static_cast(m_OldCX) / static_cast(c_cpadMax); float pCy = static_cast(m_OldCY) / static_cast(c_cpadMax); if (pCx > 1.0f) pCx = 1.0f; if (pCx < -1.0f) pCx = -1.0f; if (pCy > 1.0f) pCy = 1.0f; if (pCy < -1.0f) pCy = -1.0f; m_x360Report.sThumbLX = (short)(pCx * MAX_STICK_RANGE); m_x360Report.sThumbLY = (short)(pCy * MAX_STICK_RANGE); // Right stick if (m_OldCTX > 0 && m_OldCTX < c_cpadDeadZone) m_OldCTX = 0; if (m_OldCTY > 0 && m_OldCTY < c_cpadDeadZone) m_OldCTY = 0; if (m_OldCTX < 0 && m_OldCTX > -c_cpadDeadZone) m_OldCTX = 0; if (m_OldCTY < 0 && m_OldCTY > -c_cpadDeadZone) m_OldCTY = 0; float pCtx = (static_cast(m_OldCTX) / static_cast(c_cpadMax)) + ADDITION_CSTICK; float pCty = (static_cast(m_OldCTY) / static_cast(c_cpadMax)) + ADDITION_CSTICK; int newCTX = (int)(pCtx * MAX_STICK_RANGE); int newCTY = (int)(pCty * MAX_STICK_RANGE); if (newCTX > MAX_STICK_RANGE) newCTX = MAX_STICK_RANGE; if (newCTX < -MAX_STICK_RANGE) newCTX = -MAX_STICK_RANGE; if (newCTY > MAX_STICK_RANGE) newCTY = MAX_STICK_RANGE; if (newCTY < -MAX_STICK_RANGE) newCTY = -MAX_STICK_RANGE; m_x360Report.sThumbRX = newCTX; m_x360Report.sThumbRY = newCTY; // update if(!VIGEM_SUCCESS(vigem_target_x360_update(m_vDriver, m_x360Controller, m_x360Report))) { std::cout << "[Error] Error when submit report update to X360." << std::endl << std::flush; } m_OldUp = 0; } } void InputStreamSession::ChangeInputProfile(std::string profileName) { } void InputStreamSession::initMapKey() { m_keyMapping["A"] = FakeInput::Key_A; m_keyMapping["B"] = FakeInput::Key_B; m_keyMapping["C"] = FakeInput::Key_C; m_keyMapping["D"] = FakeInput::Key_D; m_keyMapping["E"] = FakeInput::Key_E; m_keyMapping["F"] = FakeInput::Key_F; m_keyMapping["G"] = FakeInput::Key_G; m_keyMapping["H"] = FakeInput::Key_H; m_keyMapping["I"] = FakeInput::Key_I; m_keyMapping["J"] = FakeInput::Key_J; m_keyMapping["K"] = FakeInput::Key_K; m_keyMapping["L"] = FakeInput::Key_L; m_keyMapping["M"] = FakeInput::Key_M; m_keyMapping["N"] = FakeInput::Key_N; m_keyMapping["O"] = FakeInput::Key_O; m_keyMapping["P"] = FakeInput::Key_P; m_keyMapping["Q"] = FakeInput::Key_Q; m_keyMapping["R"] = FakeInput::Key_R; m_keyMapping["S"] = FakeInput::Key_S; m_keyMapping["T"] = FakeInput::Key_T; m_keyMapping["U"] = FakeInput::Key_U; m_keyMapping["V"] = FakeInput::Key_V; m_keyMapping["W"] = FakeInput::Key_W; m_keyMapping["X"] = FakeInput::Key_X; m_keyMapping["Y"] = FakeInput::Key_Y; m_keyMapping["Z"] = FakeInput::Key_Z; m_keyMapping["0"] = FakeInput::Key_0; m_keyMapping["1"] = FakeInput::Key_1; m_keyMapping["2"] = FakeInput::Key_2; m_keyMapping["3"] = FakeInput::Key_3; m_keyMapping["4"] = FakeInput::Key_4; m_keyMapping["5"] = FakeInput::Key_5; m_keyMapping["6"] = FakeInput::Key_6; m_keyMapping["7"] = FakeInput::Key_7; m_keyMapping["8"] = FakeInput::Key_8; m_keyMapping["9"] = FakeInput::Key_9; m_keyMapping["F1"] = FakeInput::Key_F1; m_keyMapping["F2"] = FakeInput::Key_F2; m_keyMapping["F3"] = FakeInput::Key_F3; m_keyMapping["F4"] = FakeInput::Key_F4; m_keyMapping["F5"] = FakeInput::Key_F5; m_keyMapping["F6"] = FakeInput::Key_F6; m_keyMapping["F7"] = FakeInput::Key_F7; m_keyMapping["F8"] = FakeInput::Key_F8; m_keyMapping["F9"] = FakeInput::Key_F9; m_keyMapping["F10"] = FakeInput::Key_F10; m_keyMapping["F11"] = FakeInput::Key_F11; m_keyMapping["F12"] = FakeInput::Key_F12; m_keyMapping["Escape"] = FakeInput::Key_Escape; m_keyMapping["Space"] = FakeInput::Key_Space; m_keyMapping["Return"] = FakeInput::Key_Return; m_keyMapping["Backspace"] = FakeInput::Key_Backspace; m_keyMapping["Tab"] = FakeInput::Key_Tab; m_keyMapping["Shift_L"] = FakeInput::Key_Shift_L; m_keyMapping["Shift_R"] = FakeInput::Key_Shift_R; m_keyMapping["Control_L"] = FakeInput::Key_Control_L; m_keyMapping["Control_R"] = FakeInput::Key_Control_R; m_keyMapping["Alt_L"] = FakeInput::Key_Alt_L; m_keyMapping["Alt_R"] = FakeInput::Key_Alt_R; m_keyMapping["CapsLock"] = FakeInput::Key_CapsLock; m_keyMapping["NumLock"] = FakeInput::Key_NumLock; m_keyMapping["ScrollLock"] = FakeInput::Key_ScrollLock; m_keyMapping["PrintScreen"] = FakeInput::Key_PrintScreen; m_keyMapping["Insert"] = FakeInput::Key_Insert; m_keyMapping["Delete"] = FakeInput::Key_Delete; m_keyMapping["PageUP"] = FakeInput::Key_PageUP; m_keyMapping["PageDown"] = FakeInput::Key_PageDown; m_keyMapping["Home"] = FakeInput::Key_Home; m_keyMapping["End"] = FakeInput::Key_End; m_keyMapping["Left"] = FakeInput::Key_Left; m_keyMapping["Right"] = FakeInput::Key_Right; m_keyMapping["Up"] = FakeInput::Key_Up; m_keyMapping["Down"] = FakeInput::Key_Down; m_keyMapping["Numpad0"] = FakeInput::Key_Numpad0; m_keyMapping["Numpad1"] = FakeInput::Key_Numpad1; m_keyMapping["Numpad2"] = FakeInput::Key_Numpad2; m_keyMapping["Numpad3"] = FakeInput::Key_Numpad3; m_keyMapping["Numpad4"] = FakeInput::Key_Numpad4; m_keyMapping["Numpad5"] = FakeInput::Key_Numpad5; m_keyMapping["Numpad6"] = FakeInput::Key_Numpad6; m_keyMapping["Numpad7"] = FakeInput::Key_Numpad7; m_keyMapping["Numpad8"] = FakeInput::Key_Numpad8; m_keyMapping["Numpad9"] = FakeInput::Key_Numpad9; m_keyMapping["NumpadAdd"] = FakeInput::Key_NumpadAdd; m_keyMapping["NumpadSubtract"] = FakeInput::Key_NumpadSubtract; m_keyMapping["NumpadMultiply"] = FakeInput::Key_NumpadMultiply; m_keyMapping["NumpadDivide"] = FakeInput::Key_NumpadDivide; m_keyMapping["NumpadDecimal"] = FakeInput::Key_NumpadDecimal; m_keyMapping["NumpadEnter"] = FakeInput::Key_NumpadEnter; } void InputStreamSession::initVIGEM() { m_Xbox360Enable = false; // // Allocate driver connection object // m_vDriver = vigem_alloc(); // // Attempt to connect to bus driver // if(!VIGEM_SUCCESS(vigem_connect(m_vDriver))) { std::cout << "[Error] Can't connect to Virtual Controller." << std::endl << std::flush; std::cout << "-> Please ask on Discord for more information: https://discordapp.com/channels/340110838947905538/340110838947905538." << std::endl << std::flush; return; } std::cout << "[X360] Connected successfully." << std::endl << std::flush; // // Allocate target device object of type Xbox 360 Controller // m_x360Controller = vigem_target_x360_alloc(); // // Add new Xbox 360 device to bus. // // This call blocks until the device reached working state // or an error occurred. // if (!VIGEM_SUCCESS(vigem_target_add(m_vDriver, m_x360Controller))) { std::cout << "[Error] Couldn't add virtual X360 device." << std::endl << std::flush; return; } std::cout << "[X360] Added virtual x360 device successfully." << std::endl << std::flush; XUSB_REPORT_INIT(&m_x360Report); m_Xbox360Enable = true; } ================================================ FILE: PinBoxServer/PinBoxServer/InputStreamSession.h ================================================ #pragma once #ifndef _PP_INPUT_STREAM_SESSION_H_ #define _PP_INPUT_STREAM_SESSION_H_ #define BIT(n) (1U<<(n)) #include #include #include "ViGEmClient.h" /// Key values. enum { KEY_A = BIT(0), ///< A KEY_B = BIT(1), ///< B KEY_SELECT = BIT(2), ///< Select KEY_START = BIT(3), ///< Start KEY_DRIGHT = BIT(4), ///< D-Pad Right KEY_DLEFT = BIT(5), ///< D-Pad Left KEY_DUP = BIT(6), ///< D-Pad Up KEY_DDOWN = BIT(7), ///< D-Pad Down KEY_R = BIT(8), ///< R KEY_L = BIT(9), ///< L KEY_X = BIT(10), ///< X KEY_Y = BIT(11), ///< Y KEY_ZL = BIT(14), ///< ZL (New 3DS only) KEY_ZR = BIT(15), ///< ZR (New 3DS only) KEY_TOUCH = BIT(20), ///< Touch (Not actually provided by HID) KEY_CSTICK_RIGHT = BIT(24), ///< C-Stick Right (New 3DS only) KEY_CSTICK_LEFT = BIT(25), ///< C-Stick Left (New 3DS only) KEY_CSTICK_UP = BIT(26), ///< C-Stick Up (New 3DS only) KEY_CSTICK_DOWN = BIT(27), ///< C-Stick Down (New 3DS only) KEY_CPAD_RIGHT = BIT(28), ///< Circle Pad Right KEY_CPAD_LEFT = BIT(29), ///< Circle Pad Left KEY_CPAD_UP = BIT(30), ///< Circle Pad Up KEY_CPAD_DOWN = BIT(31), ///< Circle Pad Down // Generic catch-all directions KEY_UP = KEY_DUP | KEY_CPAD_UP, ///< D-Pad Up or Circle Pad Up KEY_DOWN = KEY_DDOWN | KEY_CPAD_DOWN, ///< D-Pad Down or Circle Pad Down KEY_LEFT = KEY_DLEFT | KEY_CPAD_LEFT, ///< D-Pad Left or Circle Pad Left KEY_RIGHT = KEY_DRIGHT | KEY_CPAD_RIGHT, ///< D-Pad Right or Circle Pad Right }; struct KeyMappingProfile { std::string name = ""; std::map mappings; std::map controller; bool circlePadAsMouse = false; bool ZLRAsMouseButton = false; std::string type = ""; }; class InputStreamSession { private: const short c_cpadDeadZone = 15; const short c_cpadMin = 0; const short c_cpadMax = 156; uint32_t m_OldDown; uint32_t m_OldUp; short m_OldCX; short m_OldCY; short m_OldCTX; short m_OldCTY; std::string m_currentProfile = "Default"; KeyMappingProfile* m_defaultProfile; std::map m_keyMappingProfiles; std::map m_keyMapping; void initMapKey(); void initVIGEM(); bool m_Xbox360Enable = false; PVIGEM_CLIENT m_vDriver; // xbox 360 controller PVIGEM_TARGET m_x360Controller; XUSB_REPORT m_x360Report; public: InputStreamSession(); ~InputStreamSession(); void LoadInputConfig(); void UpdateInput(uint32_t down, uint32_t up, short cx, short cy, short ctx, short cty); void ProcessInput(); void ChangeInputProfile(std::string profileName); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/PPClientSession.cpp ================================================ #include "stdafx.h" #include "PPClientSession.h" #include "PPMessage.h" #include "PPServer.h" #include "HubItem.h" #include "ServerConfig.h" void PPClientSession::InitSession(evpp::TCPConnPtr conn, PPServer* parent) { _connection = conn; _server = parent; // static buffer _receivedBuffer = (u8*)malloc(BUFFER_SIZE); _receivedBufferSize = 0; // default wait size for authentication _waitForSize = 9; } void PPClientSession::DisconnectFromServer() { if (_tmpMessage) delete _tmpMessage; //TODO: stop all stream } void PPClientSession::PrepareVideoPacketAndSend(u8* buffer, int bufferSize) { sendMessageWithCodeAndData(MSG_CODE_REQUEST_NEW_SCREEN_FRAME, buffer, bufferSize); } void PPClientSession::PrepareAudioPacketAndSend(u8* buffer, int bufferSize, uint64_t pts) { sendMessageWithCodeAndData(MSG_CODE_REQUEST_NEW_AUDIO_FRAME, buffer, bufferSize); } void PPClientSession::ProcessMessage(evpp::Buffer* msg) { //------------------------------------------------ // merge msg data into buffer memcpy(_receivedBuffer + _receivedBufferSize, msg->data(), msg->size()); // increment buffer size _receivedBufferSize += msg->size(); if (_receivedBufferSize < _waitForSize || _waitForSize == 0) return; // process thought data buffer int dataAfterProcessed = _receivedBufferSize - _waitForSize; do { // calculate data left u32 lastWaitForSize = _waitForSize; // process message data // NOTE: _waitForSize should be changed inside this function ProcessIncommingMessage(_receivedBuffer, lastWaitForSize); // shifting memory memcpy(_receivedBuffer, _receivedBuffer + lastWaitForSize, dataAfterProcessed); // update data left _receivedBufferSize = dataAfterProcessed; if (_receivedBufferSize < _waitForSize || _waitForSize == 0) break; dataAfterProcessed = _receivedBufferSize - _waitForSize; } while (dataAfterProcessed >= 0); } void PPClientSession::ProcessIncommingMessage(u8* buffer, u32 size) { if(!IsAuthenticated()) { //---------------------------------------------------- // parse for header part PPMessage* autheMsg = new PPMessage(); if (!autheMsg->ParseHeader(buffer)) { std::cout << "[Authentication Error] Vaidation code incorrect " << std::endl; sendMessageWithCode(MSG_CODE_RESULT_AUTHENTICATION_FAILED); return; } //---------------------------------------------------- // validate authentication if (autheMsg->GetMessageCode() != MSG_CODE_REQUEST_AUTHENTICATION_SESSION) { std::cout << "[Authentication Error] Invalid session type: " << autheMsg->GetMessageCode() << std::endl; sendMessageWithCode(MSG_CODE_RESULT_AUTHENTICATION_FAILED); return; } _server->ScreenCapturer->registerClientSession(this); _authenticated = true; // set waiting to a header msg _currentReadState = PPREQUEST_HEADER; _waitForSize = MSG_COMMAND_SIZE; //---------------------------------------------------- // send back to client to validate authentication successfully std::cout << "[Authentication Successed] Session: #" << _connection->remote_addr() << std::endl; sendMessageWithCode(MSG_CODE_RESULT_AUTHENTICATION_SUCCESS); }else { if (!_tmpMessage) _tmpMessage = new PPMessage(); if (_currentReadState == PPREQUEST_HEADER) { if (!_tmpMessage->ParseHeader(buffer)) { std::cout << "[Parse Message Error] Vaidation code incorrect - are you sure current is header part ?" << std::endl; _tmpMessage->ClearHeader(); return; } //---------------------------------------------------- // switch to read body part _currentReadState = PPREQUEST_BODY; _waitForSize = _tmpMessage->GetContentSize(); //---------------------------------------------------- // pre process header code if need processMessageHeader(_tmpMessage->GetMessageCode()); //---------------------------------------------------- // it content size of message is zero so we start // wait for new message if (_tmpMessage->GetContentSize() == 0) { _currentReadState = PPREQUEST_HEADER; _waitForSize = MSG_COMMAND_SIZE; } } else if (_currentReadState == PPREQUEST_BODY) { if (size == _tmpMessage->GetContentSize()) { // process body buffer processMessageBody(buffer, _tmpMessage->GetMessageCode()); // switch to read next header part _currentReadState = PPREQUEST_HEADER; _waitForSize = MSG_COMMAND_SIZE; _tmpMessage->ClearHeader(); } } } } void PPClientSession::sendMessageWithCode(u8 code) { PPMessage* msg = new PPMessage(); msg->BuildMessageHeader(code); void* buffer = msg->BuildMessageEmpty(); _connection->Send(buffer, 9); free(buffer); } void PPClientSession::sendMessageWithCodeAndData(u8 code, u8* buffer, size_t bufferSize) { PPMessage* msg = new PPMessage(); msg->BuildMessageHeader(code); void* result = msg->BuildMessage(buffer, bufferSize); _connection->Send(result, msg->GetMessageSize()); free(result); } void PPClientSession::processMessageHeader(u8 code) { switch (code) { //case MSG_CODE_REQUEST_START_SCREEN_CAPTURE: // std::cout << "Client send COMMAND: Start Stream" << std::endl; // _server->ScreenCapturer->startStream(); // break; //case MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE: // std::cout << "Client send COMMAND: Stop Stream" << std::endl; // _server->ScreenCapturer->stopStream(); // break; case MSG_CODE_REQUEST_SCREEN_RECEIVED_FRAME: break; case MSG_CODE_REQUEST_RECEIVED_AUDIO_FRAME: break; case MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE: break; case MSG_CODE_SEND_INPUT_CAPTURE: break; case MSG_CODE_REQUEST_HUB_ITEMS: { std::cout << "Client send COMMAND: Request Hub Items" << std::endl; evpp::Buffer* buf = new evpp::Buffer(); // add array size u16 count = ServerConfig::Get()->HubItems.size(); buf->Append(&count, sizeof u16); for (auto item : ServerConfig::Get()->HubItems) { // add u8 type = item->type; buf->Append(&type, sizeof u8); // add uuid u16 uuidSize = item->uuid.size(); buf->Append(&uuidSize, sizeof u16); buf->Append(item->uuid.c_str(), uuidSize); // add name u16 nameSize = item->name.size(); buf->Append(&nameSize, sizeof u16); buf->Append(item->name.c_str(), nameSize); // add thumbnail if not is monitor if (item->type != HUB_SCREEN) { buf->Append(&item->thumbSize, sizeof u32); buf->Append(item->thumbBuf, item->thumbSize); } } // send and clean up sendMessageWithCodeAndData(MSG_CODE_RECEIVED_HUB_ITEMS, (u8*)buf->data(), buf->size()); delete buf; break; } default: std::cout << "Client " << _connection->remote_addr() << " send Header UNKNOW COMMAND: " << code << std::endl; break; } } void PPClientSession::processMessageBody(u8* buffer, u8 code) { switch (code) { case MSG_CODE_REQUEST_START_SCREEN_CAPTURE: std::cout << "Client send COMMAND: Start Stream" << std::endl; _server->ScreenCapturer->startStream(); break; case MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE: std::cout << "Client send COMMAND: Stop Stream" << std::endl; _server->ScreenCapturer->stopStream(); break; //================================================ // Delete later //================================================ case MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE: { //NOTE: do those setting are useless for now. // wait for frame int8_t waitForReceived = READ_U8(buffer, 0); bool _waitForClientReceived = !(waitForReceived == 0); // smoother frame u32 _waitForFrame = READ_U32(buffer, 1); // smoother frame u32 _outputQuality = READ_U32(buffer, 5); // smoother frame u32 _outputScale = READ_U32(buffer, 9); ///----------------------------------- std::cout << "Change Stream Setting: " << std::endl; std::cout << "Smooth Frame: " << _waitForFrame << std::endl; std::cout << "Quality: " << _outputQuality << std::endl; std::cout << "Scale: " << _outputScale << std::endl; ///----------------------------------- //_server->ScreenCapturer->changeSetting(_waitForClientReceived, _waitForFrame, _outputQuality, _outputScale); break; } //================================================ // Input process //================================================ case MSG_CODE_SEND_INPUT_CAPTURE: { //-------------------------------------- //read input data u32 down = 0; memcpy(&down, buffer, 4); u32 up = 0; memcpy(&up, buffer + 4, 4); short cx = 0; memcpy(&cx, buffer + 8, 2); short cy = 0; memcpy(&cy, buffer + 10, 2); short ctx = 0; memcpy(&ctx, buffer + 12, 2); short cty = 0; memcpy(&cty, buffer + 14, 2); //-------------------------------------- _server->InputStreamer->UpdateInput(down, up, cx, cy, ctx, cty); break; } default: std::cout << "Client " << _connection->remote_addr() << " send Body UNKNOW COMMAND" << std::endl << std::flush; break; } } ================================================ FILE: PinBoxServer/PinBoxServer/PPClientSession.h ================================================ #pragma once #ifndef _PP_CLIENTSESISON_H_ #define _PP_CLIENTSESISON_H_ #include #include "PPMessage.h" // evpp #include #include #include #include #include "HubItem.h" enum PPSession_Type { PPSESSION_NONE, PPSESSION_MOVIE, PPSESSION_SCREEN_CAPTURE, PPSESSION_INPUT_CAPTURE }; #define MSG_COMMAND_SIZE 9 #define PPREQUEST_NONE 0 #define PPREQUEST_HEADER 10 #define PPREQUEST_BODY 15 // authentication code #define MSG_CODE_REQUEST_AUTHENTICATION_SESSION 1 #define MSG_CODE_RESULT_AUTHENTICATION_SUCCESS 5 #define MSG_CODE_RESULT_AUTHENTICATION_FAILED 6 // screen capture code #define MSG_CODE_REQUEST_START_SCREEN_CAPTURE 10 #define MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE 11 #define MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE 12 #define MSG_CODE_REQUEST_NEW_SCREEN_FRAME 15 #define MSG_CODE_REQUEST_SCREEN_RECEIVED_FRAME 16 #define MSG_CODE_REQUEST_NEW_AUDIO_FRAME 18 #define MSG_CODE_REQUEST_RECEIVED_AUDIO_FRAME 19 // input #define MSG_CODE_SEND_INPUT_CAPTURE 42 #define MSG_CODE_SEND_INPUT_CAPTURE_IDLE 44 #define MSG_CODE_REQUEST_HUB_ITEMS 60 #define MSG_CODE_RECEIVED_HUB_ITEMS 61 // 8Mb default size just enough #define BUFFER_SIZE 1024 * 1024 * 8 #define CHOP_N(BUFFER, COUNT, LENGTH) memmove(BUFFER, BUFFER + COUNT, LENGTH) class PPServer; class PPClientSession { private: evpp::TCPConnPtr _connection; bool _authenticated = false; u8* _receivedBuffer = nullptr; u32 _receivedBufferSize = 0; u32 _waitForSize = 0; PPMessage* _tmpMessage = nullptr; u8 _currentReadState = PPREQUEST_NONE; private: void sendMessageWithCode(u8 code); void sendMessageWithCodeAndData(u8 code, u8* buffer, size_t bufferSize); void processMessageHeader(u8 code); void processMessageBody(u8* buffer, u8 code); void ProcessIncommingMessage(u8* buffer, u32 size); public: PPServer* _server; void InitSession(evpp::TCPConnPtr conn, PPServer* parent); void ProcessMessage(evpp::Buffer* msg); void DisconnectFromServer(); bool IsAuthenticated() const { return _authenticated; } void PrepareVideoPacketAndSend(u8* buffer, int bufferSize); void PrepareAudioPacketAndSend(u8* buffer, int bufferSize, uint64_t pts); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/PPMessage.cpp ================================================ #include "stdafx.h" #include "PPMessage.h" PPMessage::~PPMessage() { if (g_content != nullptr) free(g_content); } u8* PPMessage::BuildMessage(u8* contentBuffer, u32 contentSize) { g_contentSize = contentSize; //----------------------------------------------- // alloc msg buffer block u8* msgBuffer = (u8*)malloc(sizeof(u8) * (contentSize + 9)); //----------------------------------------------- // build header u8* pointer = msgBuffer; // 1, validate code WRITE_CHAR_PTR(pointer, g_validateCode, 4); // 2, message code WRITE_U8(pointer, g_code); // 3, content size WRITE_U32(pointer, g_contentSize); //TODO: corrupted when save g_contentSize ?? //----------------------------------------------- // build content data if (g_contentSize > 0) { memcpy(msgBuffer+9, contentBuffer, contentSize); } //----------------------------------------------- return msgBuffer; } u8* PPMessage::BuildMessageEmpty() { return BuildMessage(nullptr, 0); } void PPMessage::BuildMessageHeader(u8 code) { g_code = code; } bool PPMessage::ParseHeader(u8* buffer) { if (IS_INVALID_CODE(buffer, 0)) { printf("Parse header failed. Validate code is incorrect \n"); return false; } size_t readIndex = 4; g_code = READ_U8(buffer, readIndex); readIndex += 1; g_contentSize = READ_U32(buffer, readIndex); readIndex += 4; return true; } void PPMessage::ClearHeader() { g_code = 0; g_contentSize = 0; } ================================================ FILE: PinBoxServer/PinBoxServer/PPMessage.h ================================================ #pragma once #ifndef _PP_MESSAGE_H_ #define _PP_MESSAGE_H_ #include #include #include #include typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; #define WRITE_CHAR_PTR(BUFFER, DATA, SIZE) memcpy(BUFFER, DATA, SIZE); BUFFER += SIZE; #define WRITE_U8(BUFFER, DATA) *(BUFFER++) = DATA; #define WRITE_U16(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; #define WRITE_U32(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; *(BUFFER++) = DATA >> 16; *(BUFFER++) = DATA >> 24; #define WRITE_U64(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; *(BUFFER++) = DATA >> 16; *(BUFFER++) = DATA >> 24;*(BUFFER++) = DATA >> 32;*(BUFFER++) = DATA >> 40;*(BUFFER++) = DATA >> 48;*(BUFFER++) = DATA >> 56; #define READ_U8(BUFFER, INDEX) BUFFER[INDEX]; #define READ_U16(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8; #define READ_U32(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8 | BUFFER[INDEX + 2] << 16 | BUFFER[INDEX + 3] << 24; #define READ_U32(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8 | BUFFER[INDEX + 2] << 16 | BUFFER[INDEX + 3] << 24 | BUFFER[INDEX + 3] << 32 | BUFFER[INDEX + 3] << 40 | BUFFER[INDEX + 3] << 48 | BUFFER[INDEX + 3] << 56; #define IS_INVALID_CODE(BUFFER, INDEX) BUFFER[INDEX] != 'P' || BUFFER[INDEX+1] != 'P' || BUFFER[INDEX+2] != 'B' || BUFFER[INDEX+3] != 'X' class PPMessage { private: //----------------------------------------------- // message header - 9 bytes // [4b] validate code : "PPBX" // [1b] message code : 0 to 255 - define message type // [4b] message content size //----------------------------------------------- const char g_validateCode[4] = { 'P','P','B','X' }; u8 g_code = 0; u32 g_contentSize = 0; //----------------------------------------------- // message content //----------------------------------------------- u8* g_content = nullptr; public: ~PPMessage(); u32 GetMessageSize() const { return g_contentSize + 9; } u8* GetMessageContent() { return g_content; } u32 GetContentSize() { return g_contentSize; } u8 GetMessageCode() { return g_code; } //----------------------------------------------- // NOTE: after using this message, returned data must be free whenever it sent. //----------------------------------------------- u8* BuildMessage(u8* contentBuffer, u32 contentSize); u8* BuildMessageEmpty(); void BuildMessageHeader(u8 code); bool ParseHeader(u8* buffer); void ClearHeader(); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/PPServer.cpp ================================================ #include "stdafx.h" #include "PPServer.h" #include "ServerConfig.h" #include void PPServer::PrintIPAddressList() { // Get local host name char szHostName[128] = ""; if (::gethostname(szHostName, sizeof(szHostName))) { // Error handling -> call 'WSAGetLastError()' } // Get local IP addresses struct sockaddr_in SocketAddress; struct hostent* pHost = 0; pHost = ::gethostbyname(szHostName); if (!pHost) { // Error handling -> call 'WSAGetLastError()' } char aszIPAddresses[10][16]; // maximum of ten IP addresses for (int iCnt = 0; ((pHost->h_addr_list[iCnt]) && (iCnt < 10)); ++iCnt) { memcpy(&SocketAddress.sin_addr, pHost->h_addr_list[iCnt], pHost->h_length); strcpy(aszIPAddresses[iCnt], inet_ntoa(SocketAddress.sin_addr)); std::cout << "IP: " << aszIPAddresses[iCnt] << std::endl << std::flush; } } void PPServer::InitServer() { google::InitGoogleLogging("PinBoxServer"); google::SetCommandLineOption("GLOG_minloglevel", "2"); //=========================================================================== // Init config //=========================================================================== int cfgPort = ServerConfig::Get()->ServerPort; int cfgThreadNum = ServerConfig::Get()->NetworkThread; ScreenCapturer = new ScreenCaptureSession(); ScreenCapturer->setParent(this); InputStreamer = new InputStreamSession(); //=========================================================================== // Socket server part //=========================================================================== std::string addr = "0.0.0.0:" + std::to_string(cfgPort); std::cout << "Running on address: " << addr << std::endl << std::flush; evpp::EventLoop loop; evpp::TCPServer server(&loop, addr, "PinBoxServer", cfgThreadNum); //=========================================================================== server.SetMessageCallback([&](const evpp::TCPConnPtr& conn, evpp::Buffer* msg) { PPClientSession* session = evpp::any_cast(conn->context()); if (session != nullptr) session->ProcessMessage(msg); msg->Reset(); }); //=========================================================================== server.SetConnectionCallback([&](const evpp::TCPConnPtr& conn) { std::string addrID = conn->remote_addr(); if(conn->IsConnected()) { // new client is connected std::cout << "Client: " << addrID << " connected to server!" << std::endl << std::flush; PPClientSession* session = new PPClientSession(); session->InitSession(conn, this); evpp::Any context(session); conn->set_context(context); }else { // client is disconnected evpp::Any sessionAny = conn->context(); PPClientSession* session = evpp::any_cast(sessionAny); if(session != nullptr) { std::cout << "Client: " << addrID << " disconnected to server!" << std::endl << std::flush; session->DisconnectFromServer(); } } }); server.Init(); server.Start(); //=========================================================================== // print screen //=========================================================================== std::cout << "Init Server : Successfully" << std::endl << std::flush; std::cout << "-------------------------------------------" << std::endl << std::flush; std::cout << "Please use one of those IP in your 3DS client to connect to server:" << std::endl << std::flush; std::cout << "(normally it should be the last one)" << std::endl << std::flush; std::cout << "-------------------------------------------" << std::endl << std::flush; PrintIPAddressList(); std::cout << "-------------------------------------------" << std::endl << std::flush; std::cout << "Wait for connection..." << std::endl << std::flush; //=========================================================================== loop.Run(); } ================================================ FILE: PinBoxServer/PinBoxServer/PPServer.h ================================================ #pragma once #ifndef _PP_SERVER_H__ #define _PP_SERVER_H__ // socket #include #include #include #include // evpp #include #include #include #include #include "PPClientSession.h" #include "ScreenCaptureSession.h" #include "InputStreamSession.h" class PPServer { public: static void PrintIPAddressList(); public: ScreenCaptureSession* ScreenCapturer; InputStreamSession* InputStreamer; void InitServer(); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/PinBoxServer.cpp ================================================ // PinBoxServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "PPServer.h" int main(int argc, char *argv[]) { PPServer *server = new PPServer(); server->InitServer(); return 0; } #include "winmain-inl.h" ================================================ FILE: PinBoxServer/PinBoxServer/PinBoxServer.vcxproj ================================================  Debug Win32 Release Win32 Debug x64 Release x64 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2} Win32Proj PinBoxServer 10.0.10586.0 Application true v140 Unicode Application false v140 true Unicode false Application true v140 Unicode Application false v140 true Unicode true $(ProjectDir)\..\..\ThirdParty\screen_capture_lite\include;$(ProjectDir)\..\..\ThirdParty\opus-1.2.1\include;$(ProjectDir)\..\..\ThirdParty\libopusenc\include;$(ProjectDir)\..\..\ThirdParty\FakeInput\src;$(ProjectDir)\..\..\ThirdParty\ViGEm\Include;$(ProjectDir)\..\..\ThirdParty\ffmpeg\include;$(IncludePath) $(ProjectDir)\..\..\ThirdParty\screen_capture_lite\lib\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\opus-1.2.1\win32\VS2015\Win32\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\libopusenc\win32\opusenc\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\FakeInput\bin\lib\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\ViGEm\Debug (dynamic);$(ProjectDir)\..\..\ThirdParty\ffmpeg\lib;$(LibraryPath) true false $(ProjectDir)\..\..\ThirdParty\screen_capture_lite\include;$(ProjectDir)\..\..\ThirdParty\opus-1.2.1\include;$(ProjectDir)\..\..\ThirdParty\libopusenc\include;$(ProjectDir)\..\..\ThirdParty\FakeInput\src;$(ProjectDir)\..\..\ThirdParty\ViGEm\Include;$(ProjectDir)\..\..\ThirdParty\ffmpeg\include;$(IncludePath) $(ProjectDir)\..\..\ThirdParty\screen_capture_lite\lib\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\opus-1.2.1\win32\VS2015\Win32\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\libopusenc\win32\opusenc\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\FakeInput\bin\lib\$(Configuration)\;$(ProjectDir)\..\..\ThirdParty\ViGEm\Release (dynamic);$(ProjectDir)\..\..\ThirdParty\ffmpeg\lib;$(LibraryPath) true false Use Level3 Disabled WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) true NotSet true screen_capture_lite.lib;fakeInput.lib;opus.lib;opusenc.lib;winmm.lib;ViGEmClient.lib;Dwmapi.lib;avcodec.lib;avformat.lib;avutil.lib;avdevice.lib;avfilter.lib;swresample.lib;swscale.lib;postproc.lib;%(AdditionalDependencies) Use Level3 Disabled _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 Use MaxSpeed true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true screen_capture_lite.lib;fakeInput.lib;opus.lib;opusenc.lib;winmm.lib;ViGEmClient.lib;Dwmapi.lib;avcodec.lib;avformat.lib;avutil.lib;avdevice.lib;avfilter.lib;swresample.lib;swscale.lib;postproc.lib;%(AdditionalDependencies) false Level3 Use MaxSpeed true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Create Create Create Create Text false true ================================================ FILE: PinBoxServer/PinBoxServer/PinBoxServer.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Resource Files Header Files Header Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Resource Files Resource Files ================================================ FILE: PinBoxServer/PinBoxServer/ScreenCaptureSession.cpp ================================================ #include "stdafx.h" #include "ScreenCaptureSession.h" #include "PPServer.h" #include "ServerConfig.h" #include #define ERROR_PRINT(code) printError(code) static void printError(int errorCode) { if (errorCode >= 0) return; char log[AV_ERROR_MAX_STRING_SIZE]{ 0 }; std::cout << "Error: " << av_strerror(errorCode, log, AV_ERROR_MAX_STRING_SIZE) << std::endl; } //========================================================= // FPS counter //========================================================= FPSCounter vFPS; FPSCounter captureFPS; //static FILE* testAudioOutFLAC; // test int64_t src_ch_layout = AV_CH_LAYOUT_STEREO, dst_ch_layout = AV_CH_LAYOUT_STEREO; int src_rate = 48000, dst_rate = 22050; uint8_t **src_data = NULL; int src_nb_channels = 2, dst_nb_channels = 2; int src_linesize, dst_linesize; enum AVSampleFormat src_sample_fmt = AV_SAMPLE_FMT_S16, dst_sample_fmt = AV_SAMPLE_FMT_S16; struct SwrContext *swr_ctx; ScreenCaptureSession::ScreenCaptureSession() { } ScreenCaptureSession::~ScreenCaptureSession() { // destroy screen capture m_frameGrabber->pause(); m_frameGrabber = nullptr; releaseEncoder(); //fclose(testAudioOutFLAC); } void ScreenCaptureSession::initScreenCapture() { if (Initialized) return; if (!m_server) return; Initialized = true; mFrameRate = ServerConfig::Get()->CaptureFPS; //--------------------------------------------------------------------- auto mons = SL::Screen_Capture::GetMonitors(); std::vector selectedMonitor = std::vector(); SL::Screen_Capture::Monitor monitor = mons[ServerConfig::Get()->MonitorIndex]; selectedMonitor.push_back(monitor); //--------------------------------------------------------------------- m_frameGrabber = nullptr; m_frameGrabber = SL::Screen_Capture::CreateCaptureConfiguration([&]() { return selectedMonitor; })->onNewFrame([&](const SL::Screen_Capture::Image& img, const SL::Screen_Capture::Monitor& monitor) { if (!mInitializedCodec) return; //if (!m_isStartStreaming || m_clientSession == nullptr) return; auto size = Width(img) * Height(img) * sizeof(SL::Screen_Capture::ImageBGRA); auto imgbuffer(std::make_unique(size)); Extract(img, imgbuffer.get(), size); int totalSize = 0; if (mLastFrameData == nullptr) { mLastFrameData = new FrameData(); mLastFrameData->Width = Width(img); mLastFrameData->Height = Height(img); mLastFrameData->StrideWidth = mLastFrameData->Width * 4; totalSize = mLastFrameData->StrideWidth * mLastFrameData->Height; }else { totalSize = mLastFrameData->StrideWidth * mLastFrameData->Height; } encodeAudioFrame(); // encode video encodeVideoFrame((u8*)imgbuffer.get()); })->start_capturing(); int timeDelay = 1000.0f / (float)mFrameRate; m_frameGrabber->setFrameChangeInterval(std::chrono::milliseconds(timeDelay)); //----------------------------------------------------- // decoder m_audioGrabber = new AudioStreamSession(); m_audioGrabber->StartAudioStream(); //----------------------------------------------------- // decoder iSourceWidth = monitor.Width; iSourceHeight = monitor.Height; initEncoder(); } void ScreenCaptureSession::encodeVideoFrame(u8* buf) { // encode const unsigned char *inData[1] = { buf }; int inLinesize[1] = { mLastFrameData->StrideWidth }; ERROR_PRINT(sws_scale(pVideoScaler, inData, inLinesize, 0, mLastFrameData->Height, pVideoFrame->data, pVideoFrame->linesize)); pVideoFrame->pts = iVideoFrameIndex; iVideoFrameIndex++; int ret = avcodec_send_frame(pVideoContext, pVideoFrame); ERROR_PRINT(ret); //====================================================== ret = avcodec_receive_packet(pVideoContext, pVideoPacket); ERROR_PRINT(ret); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; if (ret < 0) return; //====================================================== if(m_clientSession != nullptr) m_clientSession->PrepareVideoPacketAndSend(pVideoPacket->data, pVideoPacket->size); //====================================================== // FPS sent //====================================================== vFPS.onNewFramecounter++; if (std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - vFPS.onNewFramestart).count() >= 1000) { vFPS.currentFPS = vFPS.onNewFramecounter; vFPS.onNewFramecounter = 0; vFPS.onNewFramestart = std::chrono::high_resolution_clock::now(); } //====================================================== av_packet_unref(pVideoPacket); } void ScreenCaptureSession::encodeAudioFrame() { float factor = (float)src_rate / (float)dst_rate; u32 size = m_audioGrabber->audioBufferSize; const u32 frameSize = pAudioFrame->nb_samples * factor; const u32 readSize = frameSize * 4; while (size >= readSize) { int ret = av_frame_make_writable(pAudioFrame); if (ret < 0) { fprintf(stderr, "Fail to init Audio frame\n"); break; } m_audioGrabber->ReadFromBuffer(src_data[0], readSize); /* convert to destination format */ ret = swr_convert(swr_ctx, pAudioFrame->data, pAudioFrame->nb_samples, (const uint8_t **)src_data, frameSize); if (ret < 0) { fprintf(stderr, "Error while converting\n"); break; } pAudioFrame->pts = iAudioPts; iAudioPts += pAudioFrame->nb_samples; ret = avcodec_send_frame(pAudioContext, pAudioFrame); while (ret >= 0) { ret = avcodec_receive_packet(pAudioContext, pAudioPacket); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) break; if (ret < 0) break; //TODO: do something with packet data if (m_clientSession != nullptr) m_clientSession->PrepareAudioPacketAndSend(pAudioPacket->data, pAudioPacket->size, pAudioFrame->pts); av_packet_unref(pAudioPacket); } size = m_audioGrabber->audioBufferSize; } } void ScreenCaptureSession::initEncoder() { av_register_all(); //----------------------------------------------------------------- // init video encoder //----------------------------------------------------------------- const AVCodec* videoCodec = avcodec_find_encoder(AV_CODEC_ID_MPEG4); pVideoContext = avcodec_alloc_context3(videoCodec); // TODO: update by config here pVideoContext->bit_rate = 1200000; pVideoContext->width = 400; pVideoContext->height = 240; pVideoContext->time_base = AVRational { 1, mFrameRate }; pVideoContext->framerate = AVRational { mFrameRate, 1 }; pVideoContext->gop_size = 18; pVideoContext->max_b_frames = 2; pVideoContext->block_align = 8; pVideoContext->pix_fmt = AV_PIX_FMT_YUV420P; // Open ERROR_PRINT(avcodec_open2(pVideoContext, videoCodec, NULL)); pVideoPacket = av_packet_alloc(); pVideoFrame = av_frame_alloc(); pVideoFrame->format = pVideoContext->pix_fmt; pVideoFrame->width = pVideoContext->width; pVideoFrame->height = pVideoContext->height; ERROR_PRINT(av_frame_get_buffer(pVideoFrame, 8)); // align 8 ? pVideoScaler = sws_getContext( iSourceWidth, iSourceHeight, AV_PIX_FMT_BGRA, pVideoContext->width, pVideoContext->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, 0, 0, 0); //----------------------------------------------------------------- // init audio encoder //----------------------------------------------------------------- const AVCodec* audioCodec = avcodec_find_encoder(AV_CODEC_ID_MP2); pAudioContext = avcodec_alloc_context3(audioCodec); //pAudioContext->time_base = AVRational{ 1 , 30 }; pAudioContext->bit_rate = 48000; pAudioContext->sample_fmt = audioCodec->sample_fmts[0]; pAudioContext->sample_rate = dst_rate; pAudioContext->channels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);; pAudioContext->channel_layout = AV_CH_LAYOUT_STEREO; pAudioContext->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; int ret = avcodec_open2(pAudioContext, audioCodec, NULL); pAudioPacket = av_packet_alloc(); pAudioFrame = av_frame_alloc(); pAudioFrame->nb_samples = pAudioContext->frame_size; pAudioFrame->format = pAudioContext->sample_fmt; pAudioFrame->channel_layout = pAudioContext->channel_layout; ERROR_PRINT(av_frame_get_buffer(pAudioFrame, 0)); /* create resampler context */ swr_ctx = swr_alloc(); if (!swr_ctx) { fprintf(stderr, "Could not allocate resampler context\n"); ret = AVERROR(ENOMEM); return; } /* set options */ av_opt_set_int(swr_ctx, "in_channel_layout", src_ch_layout, 0); av_opt_set_int(swr_ctx, "in_sample_rate", src_rate, 0); av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0); av_opt_set_int(swr_ctx, "out_channel_layout", dst_ch_layout, 0); av_opt_set_int(swr_ctx, "out_sample_rate", dst_rate, 0); av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", dst_sample_fmt, 0); /* initialize the resampling context */ if ((ret = swr_init(swr_ctx)) < 0) { fprintf(stderr, "Failed to initialize the resampling context\n"); return; } float factor = (float)src_rate / (float)dst_rate; /* allocate source and destination samples buffers */ src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout); ret = av_samples_alloc_array_and_samples(&src_data, &src_linesize, src_nb_channels, factor * pAudioFrame->nb_samples, src_sample_fmt, 0); if (ret < 0) { fprintf(stderr, "Could not allocate source samples\n"); return; } // test //testAudioOutFLAC = fopen("test_audio.bin", "wb"); mInitializedCodec = true; } void ScreenCaptureSession::releaseEncoder() { // free video avcodec_free_context(&pVideoContext); av_frame_free(&pVideoFrame); av_packet_free(&pVideoPacket); // free audio avcodec_free_context(&pAudioContext); av_frame_free(&pAudioFrame); av_packet_free(&pAudioPacket); delete mLastFrameData; } void ScreenCaptureSession::setParent(PPServer* parent) { m_server = parent; } void ScreenCaptureSession::startStream() { if (m_isStartStreaming) return; m_isStartStreaming = true; iVideoFrameIndex = 0; initScreenCapture(); } void ScreenCaptureSession::stopStream() { if (!m_isStartStreaming) return; m_isStartStreaming = false; Initialized = false; // release frame grabber m_frameGrabber->pause(); m_frameGrabber = nullptr; // release audio m_audioGrabber->Pause(); // release encoder releaseEncoder(); } void ScreenCaptureSession::registerClientSession(PPClientSession* sesison) { m_clientSession = sesison; } ================================================ FILE: PinBoxServer/PinBoxServer/ScreenCaptureSession.h ================================================ #pragma once #ifndef _SCREEN_CAPTURE_SESSION_H__ #define _SCREEN_CAPTURE_SESSION_H__ // frame capture #include "ScreenCapture.h" #include "PPMessage.h" #include "PPClientSession.h" //encode #include "webp/encode.h" #include #include #include #include #include #include "AudioStreamSession.h" #include //ffmpeg extern "C" { #include #include #include #include #include #include #include #include #include #include #include "libavutil/audio_fifo.h" #include } typedef struct { u8* piece; u32 size; u8 index; u32 frameIndex; } FramePiece; typedef std::function OnClientReallyClose; #define ENCODE_TYPE_WEBP 0x01 #define ENCODE_TYPE_JPEG_TURBO 0x02 #define ENCODE_TYPE_MPEG4 0x03 #define TRANSFER_BUFFER_SIZE 0x50000 #define MEMORY_BUFFER_SIZE 0x1400000 #define MEMORY_BUFFER_PADDING 0x04 typedef struct MemoryBuffer { u8* pBufferAddr; u32 iCursor; u32 iSize; u32 iMaxSize; std::mutex* pMutex; void write(u8* buf, u32 size) { if (iSize < size) return; pMutex->lock(); memcpy(pBufferAddr + iCursor, buf, size); iCursor += size; iSize -= size; pMutex->unlock(); } int read(u8* buf, u32 size) { if (iCursor == 0) return -1; pMutex->lock(); int ret = FFMIN(iCursor, size); memcpy(buf, pBufferAddr, ret); iSize += ret; iCursor -= ret; pMutex->unlock(); return ret; } }MemoryBuffer; typedef struct FPSCounter { u32 onNewFramecounter = 0; u32 currentFPS = 0; std::chrono::time_point onNewFramestart = std::chrono::high_resolution_clock::now(); std::chrono::time_point onFrameChanged = std::chrono::high_resolution_clock::now(); }; typedef struct FrameData { uint8_t* DataAddr; int Width; int Height; int StrideWidth; bool Drew; }FrameData; class ScreenCaptureSession { private: PPServer* m_server; PPClientSession* m_clientSession = nullptr; std::shared_ptr m_frameGrabber; AudioStreamSession* m_audioGrabber; bool m_isStartStreaming = false; u8 m_encodeType = ENCODE_TYPE_MPEG4; int mFrameRate; // Video int iSourceWidth; int iSourceHeight; AVCodecContext* pVideoContext; AVPacket* pVideoPacket; AVFrame* pVideoFrame; SwsContext* pVideoScaler; u32 iVideoFrameIndex = 0; void encodeVideoFrame(u8* buf); // Audio AVCodecContext* pAudioContext; AVPacket* pAudioPacket; AVFrame* pAudioFrame; int64_t iAudioPts = 0; void encodeAudioFrame(); bool mInitializedCodec = false; u32 mLastSentFrame = 0; volatile bool mIsStopEncode = false; void initEncoder(); void releaseEncoder(); public: ScreenCaptureSession(); ~ScreenCaptureSession(); bool Initialized = false; bool mIsFirstFrame = true; FrameData* mLastFrameData = nullptr; void setParent(PPServer* parent); void startStream(); void stopStream(); void registerClientSession(PPClientSession* sesison); void initScreenCapture(); u32 currentFrame() const { return iVideoFrameIndex; } bool isStreaming() const { return m_isStartStreaming; } }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/ServerConfig.cpp ================================================ #include "stdafx.h" #include "ServerConfig.h" #include #include #include void genRandom(char *s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } ServerConfig::ServerConfig() { LoadConfig(); LoadHubItems(); } ServerConfig::~ServerConfig() { } static ServerConfig* mInstance = nullptr; ServerConfig* ServerConfig::Get() { if(mInstance == nullptr) { mInstance = new ServerConfig(); } return mInstance; } void ServerConfig::LoadConfig() { libconfig::Config configFile; try { configFile.readFile("server.cfg"); } catch (const libconfig::FileIOException& fioex) { std::cout << "[Error] Server config file was not found." << std::endl; } catch (const libconfig::ParseException& pex) { std::cout << "[Error] Server config file corrupted." << std::endl; } const libconfig::Setting& root = configFile.getRoot(); std::cout << "=========== SERVER CONFIG ===================" << std::endl; int monitor = root.lookup("monitor_index"); MonitorIndex = monitor; std::cout << " Monitor Index: " << MonitorIndex << std::endl; int captureFPS = root.lookup("capture_fps"); CaptureFPS = captureFPS; if (CaptureFPS <= 0) CaptureFPS = 30; std::cout << " FPS: " << CaptureFPS << std::endl; int networkThreads = root.lookup("network_threads"); NetworkThread = networkThreads; if (NetworkThread <= 0) NetworkThread = 2; std::cout << " Network Threads: " << NetworkThread << std::endl; int serverPort = root.lookup("server_port"); ServerPort = serverPort; if (ServerPort <= 0) ServerPort = 1234; std::cout << " Server Port: " << ServerPort << std::endl; std::cout << "=============================================" << std::endl << std::flush; } void ServerConfig::LoadHubItems() { libconfig::Config configFile; try { configFile.readFile("hub.cfg"); } catch (const libconfig::FileIOException& fioex) { std::cout << "[Error] Hub config file was not found." << std::endl; } catch (const libconfig::ParseException& pex) { std::cout << "[Error] Hub config file corrupted." << std::endl; } auto monitors = SL::Screen_Capture::GetMonitors(); for(auto mon : monitors) { HubItem *hubItem = new HubItem(); std::ostringstream stringStream; stringStream << "Monitor " << mon.Index + 1; hubItem->name = stringStream.str(); char ranUUID[100]; genRandom(ranUUID, 16); hubItem->uuid = ranUUID; hubItem->type = HUB_SCREEN; HubItems.push_back(hubItem); } const libconfig::Setting &root = configFile.getRoot(); const libconfig::Setting &hub = root["hub"]; int count = hub.getLength(); for(int i = 0; i < count; ++i) { const libconfig::Setting &item = hub[i]; HubItem *hubItem = new HubItem(); if(!(item.lookupValue("name", hubItem->name) && item.lookupValue("uuid", hubItem->uuid) && item.lookupValue("thumbImage", hubItem->thumbImage) && item.lookupValue("exePath", hubItem->exePath) && item.lookupValue("processName", hubItem->processName))) continue; // load image to buf std::ifstream thumbFile("tmp\\" + hubItem->thumbImage, std::ifstream::binary); if(!thumbFile) { std::cout << "[Error] thumbnail image was not found." << std::endl; }else { // get file size thumbFile.seekg(0, thumbFile.end); uint32_t length = thumbFile.tellg(); thumbFile.seekg(0, thumbFile.beg); hubItem->thumbSize = length; hubItem->thumbBuf = (u8*)malloc(length); thumbFile.read((char*)hubItem->thumbBuf, length); thumbFile.close(); } hubItem->type = HUB_APP; HubItems.push_back(hubItem); } } ================================================ FILE: PinBoxServer/PinBoxServer/ServerConfig.h ================================================ #pragma once #ifndef _PP_SERVER_CONFIG_H__ #define _PP_SERVER_CONFIG_H__ #include #include #include "HubItem.h" #include class ServerConfig { public: ServerConfig(); ~ServerConfig(); static ServerConfig* Get(); int MonitorIndex = 0; int CaptureFPS = 30; int NetworkThread = 2; int ServerPort = 1234; void LoadConfig(); std::vector HubItems; void LoadHubItems(); }; #endif ================================================ FILE: PinBoxServer/PinBoxServer/UIMainWindow.cpp ================================================ #include "stdafx.h" #include "UIMainWindow.h" UIMainWindow::UIMainWindow(QWidget* parent) : QMainWindow(parent), ui(new UIMainWindow) { } UIMainWindow::~UIMainWindow() { delete ui; } ================================================ FILE: PinBoxServer/PinBoxServer/UIMainWindow.h ================================================ #pragma once #include class UIMainWindow : public QMainWindow { Q_OBJECT public: explicit UIMainWindow(QWidget *parent = 0); ~UIMainWindow(); private: UIMainWindow *ui; }; ================================================ FILE: PinBoxServer/PinBoxServer/const.h ================================================ #pragma once #define RESET "\033[0m" #define BLACK "\033[30m" /* Black */ #define RED "\033[31m" /* Red */ #define GREEN "\033[32m" /* Green */ #define YELLOW "\033[33m" /* Yellow */ #define BLUE "\033[34m" /* Blue */ #define MAGENTA "\033[35m" /* Magenta */ #define CYAN "\033[36m" /* Cyan */ #define WHITE "\033[37m" /* White */ #define BOLDBLACK "\033[1m\033[30m" /* Bold Black */ #define BOLDRED "\033[1m\033[31m" /* Bold Red */ #define BOLDGREEN "\033[1m\033[32m" /* Bold Green */ #define BOLDYELLOW "\033[1m\033[33m" /* Bold Yellow */ #define BOLDBLUE "\033[1m\033[34m" /* Bold Blue */ #define BOLDMAGENTA "\033[1m\033[35m" /* Bold Magenta */ #define BOLDCYAN "\033[1m\033[36m" /* Bold Cyan */ #define BOLDWHITE "\033[1m\033[37m" /* Bold White */ ================================================ FILE: PinBoxServer/PinBoxServer/hub.cfg ================================================ //-------------------------------------------- // PinBox hub //-------------------------------------------- hub = ( { name = "Cemu"; uuid = "dd8501b5"; thumbImage = "cemu.png"; exePath = "F:\Games\Cemu\cemu_1.11.1\Cemu.exe"; processName = "Cemu 1.12.2d"; }, { name = "Cup Head"; uuid = "cadfdc5e"; thumbImage = "cuphead.png"; exePath = "F:\Games\Cuphead\Cuphead.exe"; processName = "Cuphead"; }, { name = "Pit People"; uuid = "58b09523"; thumbImage = "pitpeople.png"; exePath = "F:\Games\PitPeople\pitpeople.exe"; processName = "Pit People"; } ); ================================================ FILE: PinBoxServer/PinBoxServer/input.cfg ================================================ //-------------------------------------------- // PinBox input config //-------------------------------------------- //-------------------------------------------- // mouse speed when use circle pad // form: mouse speed * pos percent ( 0 -> 100%) * direction //-------------------------------------------- mouse_speed = 15 //-------------------------------------------- // deadzone of circle pad ( min: 0 max: 156 default: 15) // this value should be around 5 ~ 20 -> 15 is best //-------------------------------------------- circle_pad_deadzone = 15 //-------------------------------------------- // input profiles //-------------------------------------------- input_profiles = ( { //------------------------------------ // [ REQUIRE PART ] //------------------------------------ // max 255 char name = "Mouse Support"; type = "keyboard"; btn_A = "L"; btn_B = "K"; btn_X = "I"; btn_Y = "J"; btn_DPAD_UP = "W"; btn_DPAD_DOWN = "S"; btn_DPAD_LEFT = "A"; btn_DPAD_RIGHT = "D"; btn_START = "Z"; btn_SELECT = "X"; btn_L = "U"; btn_R = "O"; //------------------------------------ // [ OPTIONAL PART ] //------------------------------------ // use circle pad as mouse circle_pad_as_mouse = true; //new 3ds only zl_zr_as_mouse_button = true; // if not use as mouse then set it as button //btn_ZL = "Y"; //btn_ZR = "P"; }, { //------------------------------------ // [ REQUIRE PART ] //------------------------------------ // max 255 char name = "Xbox 360"; // simulate xbox 360 controller type = "x360"; } ); ================================================ FILE: PinBoxServer/PinBoxServer/server.cfg ================================================ //-------------------------------------------- // PinBox server config //-------------------------------------------- //-------------------------------------------- // index of monitor to capture // start from 0 to number of your monitor // eg: i have 3 monitor then index should be in range 0 .. 2 //-------------------------------------------- monitor_index = 1; //-------------------------------------------- // FPS : should be set to 30 for now //-------------------------------------------- capture_fps = 30; //-------------------------------------------- // Network threads //-------------------------------------------- network_threads = 2; //-------------------------------------------- // Server port //-------------------------------------------- server_port = 1234; ================================================ FILE: PinBoxServer/PinBoxServer/stdafx.cpp ================================================ // stdafx.cpp : source file that includes just the standard includes // PinBoxServer.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file ================================================ FILE: PinBoxServer/PinBoxServer/stdafx.h ================================================ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include #include // TODO: reference additional headers your program requires here ================================================ FILE: PinBoxServer/PinBoxServer/targetver.h ================================================ #pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include ================================================ FILE: PinBoxServer/PinBoxServer/winmain-inl.h ================================================ #pragma once namespace { struct OnApp { OnApp() { #ifdef WIN32 // Initialize Winsock 2.2 WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err) { std::cout << "WSAStartup() failed with error: %d" << err; } #endif } ~OnApp() { #ifdef WIN32 system("pause"); WSACleanup(); #endif } } __s_onexit_pause; } ================================================ FILE: PinBoxServer/PinBoxServer.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PinBoxServer", "PinBoxServer\PinBoxServer.vcxproj", "{944CB352-A2A2-4B65-AB3B-18566D0ABFA2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Debug|x64.ActiveCfg = Debug|x64 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Debug|x64.Build.0 = Debug|x64 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Debug|x86.ActiveCfg = Debug|Win32 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Debug|x86.Build.0 = Debug|Win32 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Release|x64.ActiveCfg = Release|x64 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Release|x64.Build.0 = Release|x64 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Release|x86.ActiveCfg = Release|Win32 {944CB352-A2A2-4B65-AB3B-18566D0ABFA2}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPDecoder.cpp ================================================ #include "PPDecoder.h" #include #include #include #include // 0x1000 = 4096 // 0x800 = 2048 #define READ_DELAY 0x1000 #define ERROR_PRINT(code) printError(code) void PPDecoder::printError(int errorCode) { if (errorCode >= 0) return; char log[AV_ERROR_MAX_STRING_SIZE]{ 0 }; std::cout << "Error: " << av_make_error_string(log, AV_ERROR_MAX_STRING_SIZE, errorCode) << std::endl; } PPDecoder::PPDecoder() { } PPDecoder::~PPDecoder() { } #define READ_BUFFER_SIZE 0x800 static u8* readBuffer = nullptr; static void videoDecodeThreadFunc(void* arg) { PPDecoder* self = reinterpret_cast(arg); //------------------------------------------------------- int timeDelay = 1000.0f / (float)self->mFrameRate; auto timer = new Timer(std::chrono::duration(1)); //------------------------------------------------------- readBuffer = (u8*)malloc(READ_BUFFER_SIZE + MEMORY_BUFFER_PADDING); memset(readBuffer + READ_BUFFER_SIZE, 0, MEMORY_BUFFER_PADDING); self->pVideoPacket->size = -1; int ret = 0; //------------------------------------------------------- while (true) { timer->start(); self->pVideoPacket->size = self->pVideoIOBuffer->read(self->pVideoPacket->data, READ_BUFFER_SIZE); while(self->pVideoPacket->size > 0) { self->decodeVideoStream(); } timer->wait(); } } void PPDecoder::initDecoder() { av_register_all(); initVideoStream(); } void PPDecoder::initVideoStream() { //----------------------------------------------------------------- // init video encoder //----------------------------------------------------------------- const AVCodec* videoCodec = avcodec_find_decoder(AV_CODEC_ID_MPEG4); pVideoParser = av_parser_init(videoCodec->id); pVideoContext = avcodec_alloc_context3(videoCodec); // Open int ret = avcodec_open2(pVideoContext, videoCodec, NULL); pVideoPacket = av_packet_alloc(); pVideoFrame = av_frame_alloc(); // Init custom memory buffer pVideoIOBuffer = new MemoryBuffer(); pVideoIOBuffer->pBufferAddr = (u8*)malloc(MEMORY_BUFFER_SIZE + MEMORY_BUFFER_PADDING); memset(pVideoIOBuffer->pBufferAddr + MEMORY_BUFFER_SIZE, 0, MEMORY_BUFFER_PADDING); pVideoIOBuffer->iSize = MEMORY_BUFFER_SIZE; pVideoIOBuffer->iMaxSize = MEMORY_BUFFER_SIZE; pVideoIOBuffer->iCursor = 0; pVideoIOBuffer->pMutex = new std::mutex(); } void PPDecoder::initAudioStream() { } static u8* RGB = nullptr; void PPDecoder::decodeVideoStream() { int ret = 0; ret = avcodec_send_packet(pVideoContext, pVideoPacket); if (ret < 0) return; //while (ret >= 0) { ret = avcodec_receive_frame(pVideoContext, pVideoFrame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) exit(0); //printf("saving frame %3d\n", pVideoContext->frame_number); //fflush(stdout); //---------------------------------------------- // process frame //---------------------------------------------- int w = pVideoFrame->width; int h = pVideoFrame->height; u8* Y = (u8*)pVideoFrame->data[0]; u8* U = (u8*)pVideoFrame->data[1]; u8* V = (u8*)pVideoFrame->data[2]; if (RGB == nullptr) RGB = (u8*)malloc(3 * w * h); yuv420_rgb24_std(w, h, Y, U, V, pVideoFrame->linesize[0], pVideoFrame->linesize[1], RGB, w * 3, YCBCR_JPEG); cv::Mat image(h, w, CV_8UC3, RGB); cv::cvtColor(image, image, CV_RGB2BGR); cv::imshow("video", image); cv::waitKey(1); //} } void PPDecoder::decodeAudioStream() { int ret = 0; } void PPDecoder::startDecodeThread() { initDecoder(); //------------------------------------------------------- //std::thread decodeThread = std::thread(videoDecodeThreadFunc, this); //decodeThread.detach(); } void PPDecoder::appendBuffer(u8* buffer, u32 size) { //pVideoIOBuffer->write(buffer, size); if (size <= 0) return; pVideoPacket->data = buffer; pVideoPacket->size = size; decodeVideoStream(); } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPDecoder.h ================================================ #pragma once #include "PPMessage.h" #include //#include <3ds.h> //ffmpeg extern "C" { #include #include #include #include #include #include #include #include #include #include "yuv_rgb.h" } #define MEMORY_BUFFER_SIZE 0x1400000 #define MEMORY_BUFFER_PADDING 0x04 typedef struct MemoryBuffer { u8* pBufferAddr; u32 iCursor; u32 iSize; u32 iMaxSize; std::mutex* pMutex; void write(u8* buf, u32 size) { if (iSize < size) return; pMutex->lock(); memcpy(pBufferAddr + iCursor, buf, size); iCursor += size; iSize -= size; pMutex->unlock(); } int read(u8* buf, u32 size) { if (iCursor == 0) return -1; pMutex->lock(); int ret = FFMIN(iCursor, size); memcpy(buf, pBufferAddr, ret); iSize += ret; iCursor -= ret; pMutex->unlock(); return ret; } }MemoryBuffer; #define AVIO_MIN(a,b) ((a) > (b) ? (b) : (a)) class ITimer { public: ITimer() {}; virtual ~ITimer() {} virtual void start() = 0; virtual void wait() = 0; }; template class Timer : public ITimer { std::chrono::duration Rel_Time; std::chrono::time_point StartTime; std::chrono::time_point StopTime; public: Timer(const std::chrono::duration &rel_time) : Rel_Time(rel_time) {}; virtual ~Timer() {} virtual void start() { StartTime = std::chrono::high_resolution_clock::now(); } virtual void wait() { auto duration = std::chrono::duration_cast>(std::chrono::high_resolution_clock::now() - StartTime); auto timetowait = Rel_Time - duration; if (timetowait.count() > 0) { std::this_thread::sleep_for(timetowait); } } }; class PPDecoder { public: // io context MemoryBuffer* pVideoIOBuffer; // video stream AVCodecParserContext* pVideoParser; AVCodecContext* pVideoContext; AVPacket* pVideoPacket; AVFrame* pVideoFrame; u32 iVideoFrameIndex = 0; int mFrameRate = 30; static void printError(int errorCode); public: PPDecoder(); ~PPDecoder(); void initDecoder(); void appendBuffer(u8* buffer, u32 size); void initVideoStream(); void initAudioStream(); void decodeVideoStream(); void decodeAudioStream(); void startDecodeThread(); }; ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPMessage.cpp ================================================ #include "PPMessage.h" PPMessage::~PPMessage() { if (g_content != nullptr) free(g_content); } u8* PPMessage::BuildMessage(u8* contentBuffer, u32 contentSize) { g_contentSize = contentSize; //----------------------------------------------- // alloc msg buffer block u8* msgBuffer = (u8*)malloc(sizeof(u8) * (contentSize + 9)); //----------------------------------------------- // build header u8* pointer = msgBuffer; // 1, validate code WRITE_CHAR_PTR(pointer, g_validateCode, 4); // 2, message code WRITE_U8(pointer, g_code); // 3, content size WRITE_U32(pointer, g_contentSize); //----------------------------------------------- // build content data if (g_contentSize > 0) { memcpy(msgBuffer + 9, contentBuffer, contentSize); } //----------------------------------------------- return msgBuffer; } u8* PPMessage::BuildMessageEmpty() { return BuildMessage(nullptr, 0); } void PPMessage::BuildMessageHeader(u8 code) { g_code = code; } bool PPMessage::ParseHeader(u8* buffer) { char* validateCode = (char*)malloc(4); size_t readIndex = 0; memcpy(validateCode, buffer + readIndex, 4); readIndex += 4; if (!std::strcmp(validateCode, "PPBX")) { printf("Parse header failed. Validate code is incorrect : %s", validateCode); return false; } free(validateCode); validateCode = nullptr; //----------------------------------------------------------- g_code = READ_U8(buffer, readIndex); readIndex += 1; g_contentSize = READ_U32(buffer, readIndex); readIndex += 4; return true; } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPMessage.h ================================================ #pragma once #ifndef _PP_MESSAGE_H_ #define _PP_MESSAGE_H_ #include #include #include #include typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; #define WRITE_CHAR_PTR(BUFFER, DATA, SIZE) memcpy(BUFFER, DATA, SIZE); BUFFER += SIZE; #define WRITE_U8(BUFFER, DATA) *(BUFFER++) = DATA; #define WRITE_U16(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; #define WRITE_U32(BUFFER, DATA) *(BUFFER++) = DATA; *(BUFFER++) = DATA >> 8; *(BUFFER++) = DATA >> 16; *(BUFFER++) = DATA >> 24; #define READ_U8(BUFFER, INDEX) BUFFER[INDEX]; #define READ_U16(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8; #define READ_U32(BUFFER, INDEX) BUFFER[INDEX] | BUFFER[INDEX + 1] << 8 | BUFFER[INDEX + 2] << 16 | BUFFER[INDEX + 3] << 24; #define IS_INVALID_CODE(BUFFER, INDEX) BUFFER[INDEX] != 'P' || BUFFER[INDEX+1] != 'P' || BUFFER[INDEX+2] != 'B' || BUFFER[INDEX+3] != 'X' class PPMessage { private: //----------------------------------------------- // message header - 9 bytes // [4b] validate code : "PPBX" // [1b] message code : 0 to 255 - define message type // [4b] message content size //----------------------------------------------- const char g_validateCode[4] = { 'P','P','B','X' }; u8 g_code = 0; u32 g_contentSize = 0; //----------------------------------------------- // message content //----------------------------------------------- u8* g_content = nullptr; public: ~PPMessage(); u32 GetMessageSize() const { return g_contentSize + 9; } u8* GetMessageContent() { return g_content; } u32 GetContentSize() { return g_contentSize; } u8 GetMessageCode() { return g_code; } //----------------------------------------------- // NOTE: after using this message, returned data must be free whenever it sent. //----------------------------------------------- u8* BuildMessage(u8* contentBuffer, u32 contentSize); u8* BuildMessageEmpty(); void BuildMessageHeader(u8 code); bool ParseHeader(u8* buffer); }; #endif ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPNetwork.cpp ================================================ #include "PPNetwork.h" #include #include "PPSession.h" /* * @brief: thread handler function */ void PPNetwork::ppNetwork_threadRun(void * arg) { PPNetwork* network = (PPNetwork*)arg; if (network == nullptr) return; //-------------------------------------------------- uint64_t sleepDuration = 1000000ULL * 1; while(!network->g_threadExit){ switch (network->g_connect_state) { case IDLE: { //-------------------------------------------------- // try to connect if not connected to server yet network->ppNetwork_connectToServer(); break; } case CONNECTING: { // connecting state break; } case CONNECTED: { //-------------------------------------------------- //send queue message network->ppNetwork_sendMessage(); //-------------------------------------------------- // listen to server when it connected successfully network->ppNetwork_listenToServer(); break; } case FAIL: { //-------------------------------------------------- // Exit thread when connection fail network->g_threadExit = true; break; } default: { break; } } #ifndef _WIN32 svcSleepThread(sleepDuration); #else std::this_thread::sleep_for(std::chrono::nanoseconds(sleepDuration)); #endif } //-------------------------------------------------- // close connection if thread is exit network->ppNetwork_closeConnection(); } void PPNetwork::ppNetwork_sendMessage() { //TODO: is it thread safe ? should we add mutex on this ? if (this->g_sendingMessage.size() > 0) { QueueMessage* queueMsg = (QueueMessage*)this->g_sendingMessage.front(); this->g_sendingMessage.pop(); //-------------------------------------------------- if (queueMsg->msgSize > 0 && queueMsg->msgBuffer != nullptr) { uint32_t totalSent = 0; //-------------------------------------------------------- // send message do { int sendAmount = send(this->g_sock, (char*)queueMsg->msgBuffer, queueMsg->msgSize, 0); if (sendAmount < 0) { // ERROR when send message return; } totalSent += sendAmount; } while (totalSent < queueMsg->msgSize); //std::cout << "[Queue]Session: #" << g_session->sessionID << " send message done! " << std::endl; //-------------------------------------------------------- // free message free(queueMsg->msgBuffer); delete queueMsg; } } } void PPNetwork::ppNetwork_connectToServer() { g_connect_state = CONNECTING; //-------------------------------------------------- // Trying to get address information struct addrinfo hints, *servinfo, *p; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; int rv = getaddrinfo(g_ip, g_port, &hints, &servinfo); if(rv != 0) { printf("Can't get address information.\n"); // Error: fail to get address g_connect_state = FAIL; WSACleanup(); return; } //-------------------------------------------------- // define socket g_sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); if (g_sock == -1) { printf("Can't create new socket.\n"); // Error: can't create socket g_connect_state = FAIL; freeaddrinfo(servinfo); WSACleanup(); return; } //-------------------------------------------------- // loop thought all result and connect for (p = servinfo; p != NULL; p = p->ai_next) { //-------------------------------------------------- // try to connect to server auto ret = connect(g_sock, p->ai_addr, p->ai_addrlen); if (ret == -1) { // Error: can't connect to this ai -> try next g_connect_state = FAIL; continue; } //-------------------------------------------------- // if it run here so it already connecteds g_connect_state = CONNECTED; break; } //-------------------------------------------------- // Note: check if connected if (g_connect_state == CONNECTED) { //-------------------------------------------------- // set socket to non blocking so we can easy control it //fcntl(sockManager->sock, F_SETFL, O_NONBLOCK); #ifndef _WIN32 fcntl(g_sock, F_SETFL, fcntl(g_sock, F_GETFL, 0) | O_NONBLOCK); #else unsigned long on = 1; ioctlsocket(g_sock, FIONBIO, &on); #endif //-------------------------------------------------- // callback when connected to server if (g_onConnectionSuccessed != nullptr) g_onConnectionSuccessed(nullptr, 1); printf("Connected to server.\n"); }else { printf("Could not connect to server.\n"); freeaddrinfo(servinfo); WSACleanup(); } } void PPNetwork::ppNetwork_onReceivedRequet() { //-------------------------------------------------- // NOTE: callback step //-------------------------------------------------- // we pass a copy version received buffer to where it need to process u8 *resultBuffer = (u8*)malloc(g_waitForSize); memcpy(resultBuffer, g_receivedBuffer, g_waitForSize); int32_t tmpSize = g_waitForSize; int32_t tmpTag = g_tag; //-------------------------------------------------- // free this data and point to nullptr free(g_receivedBuffer); g_receivedBuffer = nullptr; g_waitForSize = 0; g_receivedCounter = 0; g_tag = 0; //-------------------------------------------------- // this buffer need to be free whenever it finish it's job if(g_onReceivedRequest != nullptr) g_onReceivedRequest(resultBuffer, tmpSize, tmpTag); } /* * @brief: process current tmp buffer data if it have */ bool PPNetwork::ppNetwork_processTmpBufferData() { if (g_tmpReceivedBuffer != nullptr) { //-------------------------------------------------- // if this data is more than current request data int32_t pieceSize = g_tmpReceivedSize; int32_t dataLeft = 0; bool isFullyReceived = false; if(g_tmpReceivedSize >= g_waitForSize) { isFullyReceived = true; pieceSize = g_waitForSize; dataLeft = g_tmpReceivedSize - g_waitForSize; } //-------------------------------------------------- // copy data into current received buffer if (!g_receivedBuffer) g_receivedBuffer = (u8*)malloc(g_waitForSize); if (!g_receivedBuffer) return false; memcpy(g_receivedBuffer + g_receivedCounter, g_tmpReceivedBuffer, pieceSize); g_receivedCounter += pieceSize; if(isFullyReceived) { //-------------------------------------------------- // we finished current request ppNetwork_onReceivedRequet(); //-------------------------------------------------- // if there is still have data left if (dataLeft > 0) { //-------------------------------------------------- // cut off received part and create new data u8* tmpBuffer = (u8*)malloc(dataLeft); memcpy(tmpBuffer, g_tmpReceivedBuffer + pieceSize, dataLeft); g_tmpReceivedSize = dataLeft; free(g_tmpReceivedBuffer); g_tmpReceivedBuffer = tmpBuffer; // return false to stop current listen process return false; } } free(g_tmpReceivedBuffer); g_tmpReceivedBuffer = nullptr; g_tmpReceivedSize = 0; } return true; } void PPNetwork::ppNetwork_listenToServer() { //-------------------------------------------------- // If there is no order to receive any data so we just // continue our threads if (g_waitForSize <= 0) { return; } //-------------------------------------------------- // if tmp data is not null so that mean we need add this datao // into current request data // example case: 2 messages data send together from server //--------------------------------------------------- // stop process if there is have tmp buffer data and it fit // request message if (!ppNetwork_processTmpBufferData()) return; //-------------------------------------------------- // Recevie data from server const int bufferSize = 1024 * 24; // 24Kb buffer size u8* recvBuffer = (u8*)malloc(bufferSize); uint32_t recvAmount = -1; recvAmount = recv(g_sock, (char*)recvBuffer, bufferSize, 0); //-------------------------------------------------- // exit thread when have connecting problem if (recvAmount <= 0) { #ifndef _WIN32 if (errno != EWOULDBLOCK) g_threadExit = true; #else if (errno != WSAEWOULDBLOCK) g_threadExit = true; #endif //-------------------------------------------------- // free data free(recvBuffer); return; }else if(recvAmount > bufferSize) { //-------------------------------------------------- // free data free(recvBuffer); return; }else { //std::cout << "Client: " << g_session->sessionID << " recv size: " << recvAmount << std::endl; //-------------------------------------------------- if(g_receivedBuffer == nullptr) g_receivedBuffer = (u8*)malloc(g_waitForSize); //-------------------------------------------------- int32_t pieceSize = recvAmount; int32_t dataLeft = 0; bool isFullyReceived = false; //-------------------------------------------------- // check if data is fully recevied if(g_receivedCounter + recvAmount >= g_waitForSize) { pieceSize = g_waitForSize - g_receivedCounter; dataLeft = recvAmount - pieceSize; isFullyReceived = true; } //-------------------------------------------------- // copy data to final buffer memcpy(g_receivedBuffer + g_receivedCounter, recvBuffer, pieceSize); g_receivedCounter += pieceSize; //-------------------------------------------------- if (isFullyReceived) { //-------------------------------------------------- // set received request and free g_receivedBuffer ppNetwork_onReceivedRequet(); //-------------------------------------------------- // store data left into temp buffer if (dataLeft > 0) { //--------------------------------------------------- // free tmp buffer if it not null //NOTE: is it possible if going to this part without being nullptr ? if (g_tmpReceivedBuffer != nullptr) { free(g_tmpReceivedBuffer); g_tmpReceivedBuffer = nullptr; } g_tmpReceivedBuffer = (u8*)malloc(dataLeft); memcpy(g_tmpReceivedBuffer, recvBuffer + pieceSize, dataLeft); g_tmpReceivedSize = dataLeft; } } } //-------------------------------------------------- // free data free(recvBuffer); } void PPNetwork::ppNetwork_closeConnection() { if(g_connect_state == CONNECTED) { if (g_sock == -1) return; int rc = closesocket(g_sock); if(rc != 0) { // Error : ? can't close socket } g_sock = -1; g_connect_state = IDLE; } //-------------------------------------------------- //clear all buffer data if need if (g_receivedBuffer) { free(g_receivedBuffer); g_receivedBuffer = nullptr; g_waitForSize = 0; g_receivedCounter = 0; g_tag = 0; } if(g_tmpReceivedBuffer) { free(g_tmpReceivedBuffer); g_tmpReceivedBuffer = nullptr; g_tmpReceivedSize = 0; } //-------------------------------------------------- //TODO: clear all message sending buffer // for each g_sendingMessage -> delete msg //-------------------------------------------------- // callback when connection closed if(g_onConnectionClosed != nullptr) { g_onConnectionClosed(nullptr, -1); } } //=============================================================================================== // Controller functions //=============================================================================================== #define STACKSIZE (30 * 1024) void PPNetwork::Start(const char* ip, const char* port) { if (g_connect_state == IDLE) { printf("Start connect to server...\n"); g_sendingMessage = std::queue(); //--------------------------------------------------- // init variables #ifndef _WIN32 g_ip = strdup(ip); g_port = strdup(port); #else g_ip = _strdup(ip); g_port = _strdup(port); #endif g_threadExit = false; //--------------------------------------------------- // start thread #ifndef _WIN32 int32_t prio = 0; svcGetThreadPriority(&prio, CUR_THREAD_HANDLE); g_thread = threadCreate(ppNetwork_threadRun, this, STACKSIZE, prio - 1, -2, true); #else // after create we detach thread to make it continues without blocking and no need to call join. g_thread = std::thread(ppNetwork_threadRun, this); g_thread.detach(); #endif }else { // log -> already start network connection } } void PPNetwork::Stop() { g_threadExit = true; } void PPNetwork::SetRequestData(int32_t size, int32_t tag) { if(g_waitForSize > 0) { //std::cout << "Client: " << g_session->sessionID << " send wrong request data. Request for wait still have value: " << g_waitForSize << std::endl; }else { //std::cout << "Client: " << g_session->sessionID << " register wait for size: " << size << " with tag: " << tag << std::endl; g_waitForSize = size; g_tag = tag; } } //---------------------------------------------------------- // NOTE: this function will normally run on main thread //---------------------------------------------------------- void PPNetwork::SendMessageData(u8 *msgBuffer, int32_t msgSize) { if (g_connect_state == CONNECTED) { QueueMessage* msg = new QueueMessage(); msg->msgBuffer = msgBuffer; msg->msgSize = msgSize; g_sendingMessage.push(msg); }else { std::cout << "Session: #" << g_session->sessionID << " send message when not connected" << std::endl; } } PPNetwork::~PPNetwork() { free(&g_ip); free(&g_port); if (g_receivedBuffer != nullptr) free(g_receivedBuffer); if (g_tmpReceivedBuffer != nullptr) free(g_tmpReceivedBuffer); } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPNetwork.h ================================================ #pragma once #ifndef _PP_NETWORK_H_ #define _PP_NETWORK_H_ #include #include #include #include #include #include #include #include #include #include "PPMessage.h" #include #include #pragma comment(lib, "Ws2_32.lib") enum ppConectState { IDLE, CONNECTING, CONNECTED, FAIL }; typedef std::function PPNetworkReceivedRequest; typedef std::function PPNetworkCallback; typedef struct { void *msgBuffer; int32_t msgSize; } QueueMessage; class PPSession; class PPNetwork { private: // socket const char* g_ip = 0; const char* g_port = 0; u32 g_sock = -1; ppConectState g_connect_state = IDLE; // in-out variables u32 g_tag = 0; u32 g_waitForSize = 0; u32 g_receivedCounter = 0; u8* g_receivedBuffer = nullptr; u8* g_tmpReceivedBuffer = nullptr; u32 g_tmpReceivedSize = 0; // thread std::thread g_thread; volatile bool g_threadExit = false; std::queue g_sendingMessage; // callback PPNetworkReceivedRequest g_onReceivedRequest = nullptr; PPNetworkCallback g_onConnectionSuccessed = nullptr; PPNetworkCallback g_onConnectionClosed = nullptr; private: static void ppNetwork_threadRun(void * arg); void ppNetwork_listenToServer(); void ppNetwork_connectToServer(); void ppNetwork_closeConnection(); void ppNetwork_onReceivedRequet(); bool ppNetwork_processTmpBufferData(); void ppNetwork_sendMessage(); public: ~PPNetwork(); PPSession* g_session; void Start(const char *ip, const char *port); void Stop(); ppConectState GetConnectionStatus() const { return g_connect_state; } void SetRequestData(int32_t size, int32_t tag = 0); void SendMessageData(u8 *msgBuffer, int32_t msgSize); inline void SetOnReceivedRequest(PPNetworkReceivedRequest _callback) { g_onReceivedRequest = _callback; } inline void SetOnConnectionSuccessed(PPNetworkCallback _callback) { g_onConnectionSuccessed = _callback; } inline void SetOnConnectionClosed(PPNetworkCallback _callback) { g_onConnectionClosed = _callback; } }; #endif ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPSession.cpp ================================================ #include "PPSession.h" #include "PPSessionManager.h" PPSession::~PPSession() { if (g_network != nullptr) delete g_network; } void PPSession::initSession() { if (g_network != nullptr) return; g_network = new PPNetwork(); g_network->g_session = this; printf("Init new session.\n"); //------------------------------------------------------ // callback when request data is received g_network->SetOnReceivedRequest([=](u8* buffer, u32 size, u32 tag) { //------------------------------------------------------ // verify authentication //------------------------------------------------------ if (!g_authenticated) { if (tag == PPREQUEST_AUTHEN) { // check for authentication PPMessage *authenMsg = new PPMessage(); if(authenMsg->ParseHeader(buffer)) { if(authenMsg->GetMessageCode() == MSG_CODE_RESULT_AUTHENTICATION_SUCCESS) { printf("Authentication sucessfully.\n"); g_authenticated = true; if (g_onAuthenSuccessed != nullptr) g_onAuthenSuccessed(nullptr, 0); }else { printf("Authentication failed.\n"); return; } }else { printf("Authentication failed.\n"); return; } delete authenMsg; } else { printf("Client was not authentication.\n"); return; } } //------------------------------------------------------ // process data by tag switch (tag) { case PPREQUEST_HEADER: { if (!g_tmpMessage) g_tmpMessage = new PPMessage(); if (g_tmpMessage->ParseHeader(buffer)) { //std::cout << "Client: #" << sessionID << " received message header: " << (u32)g_tmpMessage->GetMessageCode() << std::endl; //---------------------------------------------------- // request body part of this message g_network->SetRequestData(g_tmpMessage->GetContentSize(), PPREQUEST_BODY); } else { delete g_tmpMessage; g_tmpMessage = nullptr; printf("Parse message header fail. remove message.\n"); } break; } case PPREQUEST_BODY: { //------------------------------------------------------ // if tmp message is null that mean this is useless data then we avoid it if (!g_tmpMessage) return; // verify buffer size with message estimate size if (size == g_tmpMessage->GetContentSize()) { // process message switch (g_sessionType) { case PPSESSION_MOVIE: { processMovieSession(buffer, size); break; } case PPSESSION_SCREEN_CAPTURE: { processScreenCaptureSession(buffer, size); break; } case PPSESSION_INPUT_CAPTURE: { processInputSession(buffer, size); break; } } //---------------------------------------------------------- // Request for next message g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); } //------------------------------------------------------ // remove message after use delete g_tmpMessage; g_tmpMessage = nullptr; break; } default: break; } //------------------------------------------------------ // free buffer after use free(buffer); }); } void PPSession::InitMovieSession() { initSession(); //-------------------------------------- // init specific for movie session g_sessionType = PPSESSION_MOVIE; printf("Init movie session.\n"); } void PPSession::InitScreenCaptureSession(PPSessionManager* manager) { g_manager = manager; initSession(); //-------------------------------------- // init specific for movie session g_sessionType = PPSESSION_SCREEN_CAPTURE; printf("Init screen capture session.\n"); //-------------------------------------- SS_framePiecesCached = std::map(); } void PPSession::InitInputCaptureSession() { initSession(); //-------------------------------------- // init specific for movie session g_sessionType = PPSESSION_INPUT_CAPTURE; printf("Init input session.\n"); } void PPSession::StartSession(const char* ip, const char* port, PPNetworkCallback authenSuccessed) { if (g_network == nullptr) return; g_onAuthenSuccessed = authenSuccessed; g_network->SetOnConnectionSuccessed([=](u8* data, u32 size) { std::cout << "Session: #" << sessionID << " send authentication message" << std::endl; //NOTE: this not called on main thread ! //-------------------------------------------------- int8_t code = 0; if (g_sessionType == PPSESSION_MOVIE) code = MSG_CODE_REQUEST_AUTHENTICATION_MOVIE; else if (g_sessionType == PPSESSION_SCREEN_CAPTURE) code = MSG_CODE_REQUEST_AUTHENTICATION_SCREEN_CAPTURE; else if (g_sessionType == PPSESSION_INPUT_CAPTURE) code = MSG_CODE_REQUEST_AUTHENTICATION_INPUT; if(code == 0) { printf("Invalid session type.\n"); return; } //-------------------------------------------------- // screen capture session authen PPMessage *authenMsg = new PPMessage(); authenMsg->BuildMessageHeader(code); u8* msgBuffer = authenMsg->BuildMessageEmpty(); //-------------------------------------------------- // send authentication message g_network->SendMessageData(msgBuffer, authenMsg->GetMessageSize()); //-------------------------------------------------- // set request to get result message g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_AUTHEN); delete authenMsg; }); g_network->SetOnConnectionClosed([=](u8* data, u32 size) { //NOTE: this not called on main thread ! std::cout << "Session: #" << sessionID << " get connection interupted" << std::endl; }); g_network->Start(ip, port); } void PPSession::CloseSession() { if (g_network == nullptr) return; g_network->Stop(); g_authenticated = false; SS_Reset(); } void PPSession::processMovieSession(u8* buffer, size_t size) { //NOTE: this not called on main thread ! //------------------------------------------------------ // process message data by message type //------------------------------------------------------ switch (g_tmpMessage->GetMessageCode()) { default: break; } } void PPSession::processScreenCaptureSession(u8* buffer, size_t size) { //NOTE: this not called on main thread ! //------------------------------------------------------ // process message data by message type //------------------------------------------------------ switch (g_tmpMessage->GetMessageCode()) { case MSG_CODE_REQUEST_NEW_SCREEN_FRAME: { try { //------------------------------------------------------ // If using waiting for new frame then we need: { //std::cout << "Session #" << sessionID << " have received: " << size << std::endl; //-------------------------------------------------- // send request that client received frame PPMessage *msgObj = new PPMessage(); msgObj->BuildMessageHeader(MSG_CODE_REQUEST_SCREEN_RECEIVED_FRAME); u8* msgBuffer = msgObj->BuildMessageEmpty(); //-------------------------------------------------- // send authentication message g_network->SendMessageData(msgBuffer, msgObj->GetMessageSize()); delete msgObj; } //-------------------------------------------------- //store packet buffer in static buffer g_manager->AppendBuffer(buffer, size); }catch(cv::Exception& e) { std::cout << e.msg << std::endl; } break; } default: break; } } void PPSession::processInputSession(u8* buffer, size_t size) { //NOTE: this not called on main thread ! //------------------------------------------------------ // process message data by message type //------------------------------------------------------ switch (g_tmpMessage->GetMessageCode()) { default: break; } } //----------------------------------------------------- // screen capture //----------------------------------------------------- void PPSession::SS_StartStream() { PPMessage *authenMsg = new PPMessage(); authenMsg->BuildMessageHeader(MSG_CODE_REQUEST_START_SCREEN_CAPTURE); u8* msgBuffer = authenMsg->BuildMessageEmpty(); g_network->SendMessageData(msgBuffer, authenMsg->GetMessageSize()); g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); SS_v_isStartStreaming = true; delete authenMsg; } void PPSession::SS_StopStream() { PPMessage *authenMsg = new PPMessage(); authenMsg->BuildMessageHeader(MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE); u8* msgBuffer = authenMsg->BuildMessageEmpty(); g_network->SendMessageData(msgBuffer, authenMsg->GetMessageSize()); g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); SS_v_isStartStreaming = false; delete authenMsg; } void PPSession::SS_ChangeSetting() { PPMessage *authenMsg = new PPMessage(); authenMsg->BuildMessageHeader(MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE); //----------------------------------------------- // alloc msg content block size_t contentSize = 13; u8* contentBuffer = (u8*)malloc(sizeof(u8) * contentSize); u8* pointer = contentBuffer; //---------------------------------------------- // setting: wait for received frame u8 _setting_waitToReceivedFrame = SS_setting_waitToReceivedFrame ? 1 : 0; WRITE_U8(pointer, _setting_waitToReceivedFrame); // setting: smooth frame number ( only activate if waitForReceivedFrame = true) WRITE_U32(pointer, SS_setting_smoothStepFrames); // setting: frame quality [0 ... 100] WRITE_U32(pointer, SS_setting_sourceQuality); // setting: frame scale [0 ... 100] WRITE_U32(pointer, SS_setting_sourceScale); //----------------------------------------------- // build message u8* msgBuffer = authenMsg->BuildMessage(contentBuffer, contentSize); g_network->SendMessageData(msgBuffer, authenMsg->GetMessageSize()); g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); delete authenMsg; } void PPSession::SS_Reset() { SS_v_isStartStreaming = false; } FramePiece* PPSession::SafeGetFramePiece(u32 index) { SS_frameCachedMutex.lock(); auto iter = SS_framePiecesCached.find(index); if(iter != SS_framePiecesCached.end()) { FramePiece* piece = iter->second; SS_framePiecesCached.erase(iter); SS_frameCachedMutex.unlock(); return piece; }else { SS_frameCachedMutex.unlock(); return nullptr; } } void PPSession::RequestForheader() { g_network->SetRequestData(MSG_COMMAND_SIZE, PPREQUEST_HEADER); } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPSession.h ================================================ #pragma once #ifndef _PP_SESSION_H_ #define _PP_SESSION_H_ //======================================================================= // PinBox Video Session // container streaming data can be movie or screen capture // With: // 1, Movie : // TODO: using ffmpeg to decode movie stream from server // TODO: support 3D movie on N3DS // TODO: mainly support RGB565 for lower size and speed up stream // 2, Screen Capture: // TODO: capture entire screen or a part of screen that config in server //----------------------------------------------------------------------- // Note: each session is running standalone and only 1 session can be run // at a time. //======================================================================= #include "PPNetwork.h" #include #include #include enum PPSession_Type { PPSESSION_NONE, PPSESSION_MOVIE, PPSESSION_SCREEN_CAPTURE, PPSESSION_INPUT_CAPTURE}; #define MSG_COMMAND_SIZE 9 #define PPREQUEST_AUTHEN 50 #define PPREQUEST_HEADER 10 #define PPREQUEST_BODY 15 // authentication code #define MSG_CODE_REQUEST_AUTHENTICATION_MOVIE 1 #define MSG_CODE_REQUEST_AUTHENTICATION_SCREEN_CAPTURE 2 #define MSG_CODE_REQUEST_AUTHENTICATION_INPUT 3 #define MSG_CODE_RESULT_AUTHENTICATION_SUCCESS 5 #define MSG_CODE_RESULT_AUTHENTICATION_FAILED 6 // screen capture code #define MSG_CODE_REQUEST_START_SCREEN_CAPTURE 10 #define MSG_CODE_REQUEST_STOP_SCREEN_CAPTURE 11 #define MSG_CODE_REQUEST_CHANGE_SETTING_SCREEN_CAPTURE 12 #define MSG_CODE_REQUEST_NEW_SCREEN_FRAME 15 #define MSG_CODE_REQUEST_SCREEN_RECEIVED_FRAME 16 #define MSG_CODE_REQUEST_NEW_AUDIO_FRAME 18 #define MSG_CODE_REQUEST_RECEIVED_AUDIO_FRAME 19 #define AUDIO_CHANNEL 0x08 typedef struct { u32 frameIndex; u32 pieceIndex; u8* piece; u32 pieceSize; void release() { if (piece != nullptr) free(piece); } } FramePiece; class PPSessionManager; class PPSession { private: PPSessionManager *g_manager; PPSession_Type g_sessionType = PPSESSION_NONE; PPNetwork* g_network = nullptr; PPMessage* g_tmpMessage = nullptr; bool g_authenticated = false; PPNetworkCallback g_onAuthenSuccessed = nullptr; private: void initSession(); void processMovieSession(u8* buffer, size_t size); void processScreenCaptureSession(u8* buffer, size_t size); void processInputSession(u8* buffer, size_t size); public: int sessionID = -1; ~PPSession(); void InitMovieSession(); void InitScreenCaptureSession(PPSessionManager* manager); void InitInputCaptureSession(); void StartSession(const char* ip ,const char* port, PPNetworkCallback authenSuccessed); void CloseSession(); //----------------------------------------------------- // screen capture //----------------------------------------------------- private: //---------------------------------------------------------------------- // profile setting typedef struct { std::string profileName = "Default"; bool waitToReceivedFrame = false; u32 smoothStepFrames = 0; u32 sourceQuality = 100; u32 sourceScale = 100; } SSProfile; //---------------------------------------------------------------------- bool SS_v_isStartStreaming = false; bool SS_setting_waitToReceivedFrame = true; u32 SS_setting_smoothStepFrames = 1; // this setting allow frame switch smoother if there is delay when received frame u32 SS_setting_sourceQuality = 50; // webp quality control u32 SS_setting_sourceScale = 75; // frame size control eg: 75% = 0.75 of real size //---------------------------------------------------------------------- // on each frame - each session store only 1 piece as a piece frame object std::map SS_framePiecesCached; std::mutex SS_frameCachedMutex; private: public: void SS_StartStream(); void SS_StopStream(); void SS_ChangeSetting(); void SS_Reset(); FramePiece* SafeGetFramePiece(u32 index); void RequestForheader(); //----------------------------------------------------- // movie //----------------------------------------------------- //----------------------------------------------------- // input //----------------------------------------------------- }; #endif ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPSessionManager.cpp ================================================ #include "PPSessionManager.h" PPSessionManager::PPSessionManager() { } PPSessionManager::~PPSessionManager() { } void PPSessionManager::InitScreenCapture(u32 numberOfSessions) { m_decoder = new PPDecoder(); m_decoder->startDecodeThread(); if (numberOfSessions <= 0) numberOfSessions = 1; if (m_screenCaptureSessions.size() > 0) return; m_screenCaptureSessions = std::vector(); for(int i = 0; i < numberOfSessions; i++) { PPSession* session = new PPSession(); session->sessionID = i; session->InitScreenCaptureSession(this); m_screenCaptureSessions.push_back(session); } } void PPSessionManager::StartStreaming(const char* ip, const char* port) { if (m_staticVideoBuffer == nullptr) { m_staticVideoBuffer = (u8*)malloc(VideoBufferSize); m_videoBufferSize = 0; m_videoBufferCursor = 0; } //============================================== m_currentDisplayFrame = 0; m_frameTracker.clear(); m_connectedSession = 0; for (int i = 0; i < m_screenCaptureSessions.size(); i++) { // start connect all session to server m_screenCaptureSessions[i]->StartSession(ip, port, [=](u8* data, u32 code) { m_connectedSession++; if(m_connectedSession == m_screenCaptureSessions.size()) { // when all session is authenticated // start streaming here std::cout << "All sessions is connected to server : Start Streaming" << std::endl; _startStreaming(); } }); } } void PPSessionManager::StopStreaming() { for (int i = 0; i < m_screenCaptureSessions.size(); i++) { m_screenCaptureSessions[i]->SS_StopStream(); } } void PPSessionManager::Close() { for (int i = 0; i < m_screenCaptureSessions.size(); i++) { m_screenCaptureSessions[i]->CloseSession(); } } void PPSessionManager::AppendBuffer(u8* buffer, u32 size) { m_decoder->appendBuffer(buffer, size); //memmove(m_staticVideoBuffer + m_videoBufferSize, buffer, size); //m_videoBufferSize += size; } void PPSessionManager::DecodeVideo() { } void PPSessionManager::_startStreaming() { m_screenCaptureSessions[0]->SS_ChangeSetting(); m_screenCaptureSessions[0]->SS_StartStream(); for (int i = 1; i < m_screenCaptureSessions.size(); i++) { m_screenCaptureSessions[i]->RequestForheader(); } } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PPSessionManager.h ================================================ #pragma once #include #include "PPSession.h" #include #include "opusfile.h" #include "PPDecoder.h" #ifdef _WIN32 //=========================================================== // for test only // openCV #include #include #include #include //=========================================================== #endif #define VideoBufferSize 0xA00000 class PPSessionManager { private: PPDecoder* m_decoder; std::vector m_screenCaptureSessions; int m_commandSessionIndex = 0; u32 m_connectedSession = 0; void _startStreaming(); std::map m_frameTracker; std::mutex m_frameTrackerMutex; u32 m_currentDisplayFrame = 0; public: PPSessionManager(); ~PPSessionManager(); u8* m_staticVideoBuffer = nullptr; u32 m_videoBufferCursor = 0; u32 m_videoBufferSize = 0; void InitScreenCapture(u32 numberOfSessions); void StartStreaming(const char* ip, const char* port); void StopStreaming(); void Close(); void AppendBuffer(u8* buffer, u32 size); void DecodeVideo(); }; ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PinBoxTestProject.vcxproj ================================================  Debug Win32 Release Win32 Debug x64 Release x64 {901BAB37-7D47-4095-9D2A-F203382FDA88} PinBoxTestProject 10.0.10586.0 Application true v140 MultiByte Application false v140 true MultiByte Application true v140 MultiByte Application false v140 true MultiByte $(VC_IncludePath);$(WindowsSDK_IncludePath);E:\3ds\PinBoxStreaming\ThirdParty\opus-1.2.1\include;E:\3ds\PinBoxStreaming\ThirdParty\opusfile-0.9\include Level3 Disabled true _CRT_SECURE_NO_WARNINGS;_STDC_CONSTANT_MACROS;_MBCS;%(PreprocessorDefinitions) Level3 Disabled true Level3 MaxSpeed true true true true true Level3 MaxSpeed true true true true true ================================================ FILE: PinBoxTestProject/PinBoxTestProject/PinBoxTestProject.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: PinBoxTestProject/PinBoxTestProject/main.cpp ================================================ #include #include "PPSessionManager.h" #define __STDC_CONSTANT_MACROS void updateSessionManager(void* arg) { PPSessionManager* sm = (PPSessionManager*)arg; if( sm != nullptr) { while(true) { sm->DecodeVideo(); } } } int main() { #ifdef _WIN32 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); #endif std::cout << "==============================================================\n"; std::cout << "= Test application for PinBox. Simulation client side (3ds) =\n"; std::cout << "==============================================================\n"; PPSessionManager* sm = new PPSessionManager(); sm->InitScreenCapture(1); std::thread g_thread = std::thread(updateSessionManager, sm); g_thread.detach(); std::cout << "Press Q to exit.\nInput: "; char input; while(true) { std::cin >> input; if (input == 'q') break; if(input == 'a') { sm->StartStreaming("192.168.31.183", "1234"); } if (input == 's') { sm->StopStreaming(); } input = ' '; //----------------------------------------- } std::cout << "\nClosing session.\n"; sm->Close(); return 0; } ================================================ FILE: PinBoxTestProject/PinBoxTestProject/yuv_rgb.c ================================================ // Copyright 2016 Adrien Descamps // Distributed under BSD 3-Clause License #include "yuv_rgb.h" //#include #include uint8_t clamp(int16_t value) { return value<0 ? 0 : (value>255 ? 255 : value); } // Definitions // // E'R, E'G, E'B, E'Y, E'Cb and E'Cr refer to the analog signals // E'R, E'G, E'B and E'Y range is [0:1], while E'Cb and E'Cr range is [-0.5:0.5] // R, G, B, Y, Cb and Cr refer to the digitalized values // The digitalized values can use their full range ([0:255] for 8bit values), // or a subrange (typically [16:235] for Y and [16:240] for CbCr). // We assume here that RGB range is always [0:255], since it is the case for // most digitalized images. // For 8bit values : // * Y = round((YMax-YMin)*E'Y + YMin) // * Cb = round((CbRange)*E'Cb + 128) // * Cr = round((CrRange)*E'Cr + 128) // Where *Min and *Max are the range of each channel // // In the analog domain , the RGB to YCbCr transformation is defined as: // * E'Y = Rf*E'R + Gf*E'G + Bf*E'B // Where Rf, Gf and Bf are constants defined in each standard, with // Rf + Gf + Bf = 1 (necessary to ensure that E'Y range is [0:1]) // * E'Cb = (E'B - E'Y) / CbNorm // * E'Cr = (E'R - E'Y) / CrNorm // Where CbNorm and CrNorm are constants, dependent of Rf, Gf, Bf, computed // to normalize to a [-0.5:0.5] range : CbNorm=2*(1-Bf) and CrNorm=2*(1-Rf) // // Algorithms // // Most operations will be made in a fixed point format for speed, using // N bits of precision. In next section the [x] convention is used for // a fixed point rounded value, that is (int being the c type conversion) // * [x] = int(x*(2^N)+0.5) // N can be different for each factor, we simply use the highest value // that will not overflow in 16 bits intermediate variables. //. // For RGB to YCbCr conversion, we start by generating a pseudo Y value // (noted Y') in fixed point format, using the full range for now. // * Y' = ([Rf]*R + [Gf]*G + [Bf]*B)>>N // We can then compute Cb and Cr by // * Cb = ((B - Y')*[CbRange/(255*CbNorm)])>>N + 128 // * Cr = ((R - Y')*[CrRange/(255*CrNorm)])>>N + 128 // And finally, we normalize Y to its digital range // * Y = (Y'*[(YMax-YMin)/255])>>N + YMin // // For YCbCr to RGB conversion, we first compute the full range Y' value : // * Y' = ((Y-YMin)*[255/(YMax-YMin)])>>N // We can then compute B and R values by : // * B = ((Cb-128)*[(255*CbNorm)/CbRange])>>N + Y' // * R = ((Cr-128)*[(255*CrNorm)/CrRange])>>N + Y' // And finally, for G we know that: // * G = (Y' - (Rf*R + Bf*B)) / Gf // From above: // * G = (Y' - Rf * ((Cr-128)*(255*CrNorm)/CrRange + Y') - Bf * ((Cb-128)*(255*CbNorm)/CbRange + Y')) / Gf // Since 1-Rf-Bf=Gf, we can take Y' out of the division by Gf, and we get: // * G = Y' - (Cr-128)*Rf/Gf*(255*CrNorm)/CrRange - (Cb-128)*Bf/Gf*(255*CbNorm)/CbRange // That we can compute, with fixed point arithmetic, by // * G = Y' - ((Cr-128)*[Rf/Gf*(255*CrNorm)/CrRange] + (Cb-128)*[Bf/Gf*(255*CbNorm)/CbRange])>>N // // Note : in ITU-T T.871(JPEG), Y=Y', so that part could be optimized out #define FIXED_POINT_VALUE(value, precision) ((int)(((value)*(1<r_factor*rgb_ptr1[0] + param->g_factor*rgb_ptr1[1] + param->b_factor*rgb_ptr1[2])>>8; u_tmp = rgb_ptr1[2]-y_tmp; v_tmp = rgb_ptr1[0]-y_tmp; y_ptr1[0]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr1[3] + param->g_factor*rgb_ptr1[4] + param->b_factor*rgb_ptr1[5])>>8; u_tmp += rgb_ptr1[5]-y_tmp; v_tmp += rgb_ptr1[3]-y_tmp; y_ptr1[1]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr2[0] + param->g_factor*rgb_ptr2[1] + param->b_factor*rgb_ptr2[2])>>8; u_tmp += rgb_ptr2[2]-y_tmp; v_tmp += rgb_ptr2[0]-y_tmp; y_ptr2[0]=((y_tmp*param->y_factor)>>7) + param->y_offset; y_tmp = (param->r_factor*rgb_ptr2[3] + param->g_factor*rgb_ptr2[4] + param->b_factor*rgb_ptr2[5])>>8; u_tmp += rgb_ptr2[5]-y_tmp; v_tmp += rgb_ptr2[3]-y_tmp; y_ptr2[1]=((y_tmp*param->y_factor)>>7) + param->y_offset; u_ptr[0] = (((u_tmp>>2)*param->cb_factor)>>8) + 128; v_ptr[0] = (((v_tmp>>2)*param->cb_factor)>>8) + 128; rgb_ptr1 += 6; rgb_ptr2 += 6; y_ptr1 += 2; y_ptr2 += 2; u_ptr += 1; v_ptr += 1; } } } void yuv420_rgb24_std( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-1); x+=2) { int8_t u_tmp, v_tmp; u_tmp = u_ptr[0]-128; v_tmp = v_ptr[0]-128; //compute Cb Cr color offsets, common to four pixels int16_t b_cb_offset, r_cr_offset, g_cbcr_offset; b_cb_offset = (param->cb_factor*u_tmp)>>6; r_cr_offset = (param->cr_factor*v_tmp)>>6; g_cbcr_offset = (param->g_cb_factor*u_tmp + param->g_cr_factor*v_tmp)>>7; int16_t y_tmp; y_tmp = (param->y_factor*(y_ptr1[0]-param->y_offset))>>7; rgb_ptr1[0] = clamp(y_tmp + r_cr_offset); rgb_ptr1[1] = clamp(y_tmp - g_cbcr_offset); rgb_ptr1[2] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr1[1]-param->y_offset))>>7; rgb_ptr1[3] = clamp(y_tmp + r_cr_offset); rgb_ptr1[4] = clamp(y_tmp - g_cbcr_offset); rgb_ptr1[5] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr2[0]-param->y_offset))>>7; rgb_ptr2[0] = clamp(y_tmp + r_cr_offset); rgb_ptr2[1] = clamp(y_tmp - g_cbcr_offset); rgb_ptr2[2] = clamp(y_tmp + b_cb_offset); y_tmp = (param->y_factor*(y_ptr2[1]-param->y_offset))>>7; rgb_ptr2[3] = clamp(y_tmp + r_cr_offset); rgb_ptr2[4] = clamp(y_tmp - g_cbcr_offset); rgb_ptr2[5] = clamp(y_tmp + b_cb_offset); rgb_ptr1 += 6; rgb_ptr2 += 6; y_ptr1 += 2; y_ptr2 += 2; u_ptr += 1; v_ptr += 1; } } } #ifdef __SSE2__ //see rgb.txt #define UNPACK_RGB24_32_STEP(RS1, RS2, RS3, RS4, RS5, RS6, RD1, RD2, RD3, RD4, RD5, RD6) \ RD1 = _mm_unpacklo_epi8(RS1, RS4); \ RD2 = _mm_unpackhi_epi8(RS1, RS4); \ RD3 = _mm_unpacklo_epi8(RS2, RS5); \ RD4 = _mm_unpackhi_epi8(RS2, RS5); \ RD5 = _mm_unpacklo_epi8(RS3, RS6); \ RD6 = _mm_unpackhi_epi8(RS3, RS6); #define RGB2YUV_16(R, G, B, Y, U, V) \ Y = _mm_add_epi16(_mm_mullo_epi16(R, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(G, _mm_set1_epi16(param->g_factor))); \ Y = _mm_add_epi16(Y, _mm_mullo_epi16(B, _mm_set1_epi16(param->b_factor))); \ Y = _mm_srli_epi16(Y, 8); \ U = _mm_mullo_epi16(_mm_sub_epi16(B, Y), _mm_set1_epi16(param->cb_factor)); \ U = _mm_add_epi16(_mm_srai_epi16(U, 8), _mm_set1_epi16(128)); \ V = _mm_mullo_epi16(_mm_sub_epi16(R, Y), _mm_set1_epi16(param->cr_factor)); \ V = _mm_add_epi16(_mm_srai_epi16(V, 8), _mm_set1_epi16(128)); \ Y = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(Y, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); #define RGB2YUV_32 \ __m128i r_16, g_16, b_16; \ __m128i y1_16, y2_16, cb1_16, cb2_16, cr1_16, cr2_16, Y, cb, cr; \ __m128i tmp1, tmp2, tmp3, tmp4, tmp5, tmp6; \ __m128i rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1)), \ rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+16)), \ rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+32)), \ rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2)), \ rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+16)), \ rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+32)); \ /* unpack rgb24 data to r, g and b data in separate channels*/ \ /* see rgb.txt to get an idea of the algorithm, note that we only go to the next to last step*/ \ /* here, because averaging in horizontal direction is easier like this*/ \ /* The last step is applied further on the Y channel only*/ \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ /* first compute Y', (B-Y') and (R-Y'), in 16bits values, for the first line */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are saved*/ \ r_16 = _mm_unpacklo_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb1_16 = _mm_sub_epi16(b_16, y1_16); \ cr1_16 = _mm_sub_epi16(r_16, y1_16); \ r_16 = _mm_unpacklo_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y2_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr1), Y); \ /* same for the second line, compute Y', (B-Y') and (R-Y'), in 16bits values */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are added to the previous values*/ \ r_16 = _mm_unpackhi_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y1_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y1_16)); \ r_16 = _mm_unpackhi_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb1_16 = _mm_add_epi16(cb1_16, _mm_sub_epi16(b_16, y2_16)); \ cr1_16 = _mm_add_epi16(cr1_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr2), Y); \ /* Rescale Cb and Cr to their final range */ \ cb1_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cb1_16, 2), _mm_set1_epi16(param->cb_factor)), 8), _mm_set1_epi16(128)); \ cr1_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cr1_16, 2), _mm_set1_epi16(param->cr_factor)), 8), _mm_set1_epi16(128)); \ \ /* do the same again with next data */ \ rgb1 = LOAD_SI128((const __m128i*)(rgb_ptr1+48)), \ rgb2 = LOAD_SI128((const __m128i*)(rgb_ptr1+64)), \ rgb3 = LOAD_SI128((const __m128i*)(rgb_ptr1+80)), \ rgb4 = LOAD_SI128((const __m128i*)(rgb_ptr2+48)), \ rgb5 = LOAD_SI128((const __m128i*)(rgb_ptr2+64)), \ rgb6 = LOAD_SI128((const __m128i*)(rgb_ptr2+80)); \ /* unpack rgb24 data to r, g and b data in separate channels*/ \ /* see rgb.txt to get an idea of the algorithm, note that we only go to the next to last step*/ \ /* here, because averaging in horizontal direction is easier like this*/ \ /* The last step is applied further on the Y channel only*/ \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ UNPACK_RGB24_32_STEP(rgb1, rgb2, rgb3, rgb4, rgb5, rgb6, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6) \ UNPACK_RGB24_32_STEP(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, rgb1, rgb2, rgb3, rgb4, rgb5, rgb6) \ /* first compute Y', (B-Y') and (R-Y'), in 16bits values, for the first line */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are saved*/ \ r_16 = _mm_unpacklo_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb2_16 = _mm_sub_epi16(b_16, y1_16); \ cr2_16 = _mm_sub_epi16(r_16, y1_16); \ r_16 = _mm_unpacklo_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpacklo_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpacklo_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y2_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr1+16), Y); \ /* same for the second line, compute Y', (B-Y') and (R-Y'), in 16bits values */ \ /* Y is saved for each pixel, while only sums of (B-Y') and (R-Y') for pairs of adjacents pixels are added to the previous values*/ \ r_16 = _mm_unpackhi_epi8(rgb1, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb2, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb3, _mm_setzero_si128()); \ y1_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y1_16 = _mm_add_epi16(y1_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y1_16 = _mm_srli_epi16(y1_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y1_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y1_16)); \ r_16 = _mm_unpackhi_epi8(rgb4, _mm_setzero_si128()); \ g_16 = _mm_unpackhi_epi8(rgb5, _mm_setzero_si128()); \ b_16 = _mm_unpackhi_epi8(rgb6, _mm_setzero_si128()); \ y2_16 = _mm_add_epi16(_mm_mullo_epi16(r_16, _mm_set1_epi16(param->r_factor)), \ _mm_mullo_epi16(g_16, _mm_set1_epi16(param->g_factor))); \ y2_16 = _mm_add_epi16(y2_16, _mm_mullo_epi16(b_16, _mm_set1_epi16(param->b_factor))); \ y2_16 = _mm_srli_epi16(y2_16, 8); \ cb2_16 = _mm_add_epi16(cb2_16, _mm_sub_epi16(b_16, y2_16)); \ cr2_16 = _mm_add_epi16(cr2_16, _mm_sub_epi16(r_16, y2_16)); \ /* Rescale Y' to Y, pack it to 8bit values and save it */ \ y1_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y1_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ y2_16 = _mm_add_epi16(_mm_srli_epi16(_mm_mullo_epi16(y2_16, _mm_set1_epi16(param->y_factor)), 7), _mm_set1_epi16(param->y_offset)); \ Y = _mm_packus_epi16(y1_16, y2_16); \ Y = _mm_unpackhi_epi8(_mm_slli_si128(Y, 8), Y); \ SAVE_SI128((__m128i*)(y_ptr2+16), Y); \ /* Rescale Cb and Cr to their final range */ \ cb2_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cb2_16, 2), _mm_set1_epi16(param->cb_factor)), 8), _mm_set1_epi16(128)); \ cr2_16 = _mm_add_epi16(_mm_srai_epi16(_mm_mullo_epi16(_mm_srai_epi16(cr2_16, 2), _mm_set1_epi16(param->cr_factor)), 8), _mm_set1_epi16(128)); \ /* Pack and save Cb Cr */ \ cb = _mm_packus_epi16(cb1_16, cb2_16); \ cr = _mm_packus_epi16(cr1_16, cr2_16); \ SAVE_SI128((__m128i*)(u_ptr), cb); \ SAVE_SI128((__m128i*)(v_ptr), cr); void rgb24_yuv420_sse(uint32_t width, uint32_t height, const uint8_t *RGB, uint32_t RGB_stride, uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_load_si128 #define SAVE_SI128 _mm_stream_si128 const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; for(x=0; x<(width-31); x+=32) { RGB2YUV_32 rgb_ptr1+=96; rgb_ptr2+=96; y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; } } #undef LOAD_SI128 #undef SAVE_SI128 } void rgb24_yuv420_sseu(uint32_t width, uint32_t height, const uint8_t *RGB, uint32_t RGB_stride, uint8_t *Y, uint8_t *U, uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_loadu_si128 #define SAVE_SI128 _mm_storeu_si128 const RGB2YUVParam *const param = &(RGB2YUV[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; for(x=0; x<(width-31); x+=32) { RGB2YUV_32 rgb_ptr1+=96; rgb_ptr2+=96; y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; } } #undef LOAD_SI128 #undef SAVE_SI128 } #endif #ifdef __SSE2__ #define UV2RGB_16(U,V,R1,G1,B1,R2,G2,B2) \ r_tmp = _mm_srai_epi16(_mm_mullo_epi16(V, _mm_set1_epi16(param->cr_factor)), 6); \ g_tmp = _mm_srai_epi16(_mm_add_epi16( \ _mm_mullo_epi16(U, _mm_set1_epi16(param->g_cb_factor)), \ _mm_mullo_epi16(V, _mm_set1_epi16(param->g_cr_factor))), 7); \ b_tmp = _mm_srai_epi16(_mm_mullo_epi16(U, _mm_set1_epi16(param->cb_factor)), 6); \ R1 = _mm_unpacklo_epi16(r_tmp, r_tmp); \ G1 = _mm_unpacklo_epi16(g_tmp, g_tmp); \ B1 = _mm_unpacklo_epi16(b_tmp, b_tmp); \ R2 = _mm_unpackhi_epi16(r_tmp, r_tmp); \ G2 = _mm_unpackhi_epi16(g_tmp, g_tmp); \ B2 = _mm_unpackhi_epi16(b_tmp, b_tmp); \ #define ADD_Y2RGB_16(Y1,Y2,R1,G1,B1,R2,G2,B2) \ Y1 = _mm_srai_epi16(_mm_mullo_epi16(Y1, _mm_set1_epi16(param->y_factor)), 7); \ Y2 = _mm_srai_epi16(_mm_mullo_epi16(Y2, _mm_set1_epi16(param->y_factor)), 7); \ \ R1 = _mm_add_epi16(Y1, R1); \ G1 = _mm_sub_epi16(Y1, G1); \ B1 = _mm_add_epi16(Y1, B1); \ R2 = _mm_add_epi16(Y2, R2); \ G2 = _mm_sub_epi16(Y2, G2); \ B2 = _mm_add_epi16(Y2, B2); \ #define PACK_RGB24_32_STEP(RS1, RS2, RS3, RS4, RS5, RS6, RD1, RD2, RD3, RD4, RD5, RD6) \ RD1 = _mm_packus_epi16(_mm_and_si128(RS1,_mm_set1_epi16(0xFF)), _mm_and_si128(RS2,_mm_set1_epi16(0xFF))); \ RD2 = _mm_packus_epi16(_mm_and_si128(RS3,_mm_set1_epi16(0xFF)), _mm_and_si128(RS4,_mm_set1_epi16(0xFF))); \ RD3 = _mm_packus_epi16(_mm_and_si128(RS5,_mm_set1_epi16(0xFF)), _mm_and_si128(RS6,_mm_set1_epi16(0xFF))); \ RD4 = _mm_packus_epi16(_mm_srli_epi16(RS1,8), _mm_srli_epi16(RS2,8)); \ RD5 = _mm_packus_epi16(_mm_srli_epi16(RS3,8), _mm_srli_epi16(RS4,8)); \ RD6 = _mm_packus_epi16(_mm_srli_epi16(RS5,8), _mm_srli_epi16(RS6,8)); \ #define PACK_RGB24_32(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ PACK_RGB24_32_STEP(RGB1, RGB2, RGB3, RGB4, RGB5, RGB6, R1, R2, G1, G2, B1, B2) \ PACK_RGB24_32_STEP(R1, R2, G1, G2, B1, B2, RGB1, RGB2, RGB3, RGB4, RGB5, RGB6) \ #define YUV2RGB_32 \ __m128i r_tmp, g_tmp, b_tmp; \ __m128i r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2; \ __m128i r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2; \ __m128i y_16_1, y_16_2; \ \ __m128i u = LOAD_SI128((const __m128i*)(u_ptr)); \ __m128i v = LOAD_SI128((const __m128i*)(v_ptr)); \ u = _mm_add_epi8(u, _mm_set1_epi8(-128)); \ v = _mm_add_epi8(v, _mm_set1_epi8(-128)); \ \ /* process first 16 pixels of first line */\ __m128i u_16 = _mm_srai_epi16(_mm_unpacklo_epi8(u, u), 8); \ __m128i v_16 = _mm_srai_epi16(_mm_unpacklo_epi8(v, v), 8); \ \ UV2RGB_16(u_16, v_16, r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2) \ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ __m128i y = LOAD_SI128((const __m128i*)(y_ptr1)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_11 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_11 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_11 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process first 16 pixels of second line */\ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr2)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_21 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_21 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_21 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process last 16 pixels of first line */\ u_16 = _mm_srai_epi16(_mm_unpackhi_epi8(u, u), 8); \ v_16 = _mm_srai_epi16(_mm_unpackhi_epi8(v, v), 8); \ \ UV2RGB_16(u_16, v_16, r_uv_16_1, g_uv_16_1, b_uv_16_1, r_uv_16_2, g_uv_16_2, b_uv_16_2) \ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr1+16)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_12 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_12 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_12 = _mm_packus_epi16(b_16_1, b_16_2); \ \ /* process last 16 pixels of second line */\ r_16_1=r_uv_16_1; g_16_1=g_uv_16_1; b_16_1=b_uv_16_1; \ r_16_2=r_uv_16_2; g_16_2=g_uv_16_2; b_16_2=b_uv_16_2; \ \ y = LOAD_SI128((const __m128i*)(y_ptr2+16)); \ y = _mm_sub_epi8(y, _mm_set1_epi8(param->y_offset)); \ y_16_1 = _mm_unpacklo_epi8(y, _mm_setzero_si128()); \ y_16_2 = _mm_unpackhi_epi8(y, _mm_setzero_si128()); \ \ ADD_Y2RGB_16(y_16_1, y_16_2, r_16_1, g_16_1, b_16_1, r_16_2, g_16_2, b_16_2) \ \ __m128i r_8_22 = _mm_packus_epi16(r_16_1, r_16_2); \ __m128i g_8_22 = _mm_packus_epi16(g_16_1, g_16_2); \ __m128i b_8_22 = _mm_packus_epi16(b_16_1, b_16_2); \ \ __m128i rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6; \ \ PACK_RGB24_32(r_8_11, r_8_12, g_8_11, g_8_12, b_8_11, b_8_12, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6) \ SAVE_SI128((__m128i*)(rgb_ptr1), rgb_1); \ SAVE_SI128((__m128i*)(rgb_ptr1+16), rgb_2); \ SAVE_SI128((__m128i*)(rgb_ptr1+32), rgb_3); \ SAVE_SI128((__m128i*)(rgb_ptr1+48), rgb_4); \ SAVE_SI128((__m128i*)(rgb_ptr1+64), rgb_5); \ SAVE_SI128((__m128i*)(rgb_ptr1+80), rgb_6); \ \ PACK_RGB24_32(r_8_21, r_8_22, g_8_21, g_8_22, b_8_21, b_8_22, rgb_1, rgb_2, rgb_3, rgb_4, rgb_5, rgb_6) \ SAVE_SI128((__m128i*)(rgb_ptr2), rgb_1); \ SAVE_SI128((__m128i*)(rgb_ptr2+16), rgb_2); \ SAVE_SI128((__m128i*)(rgb_ptr2+32), rgb_3); \ SAVE_SI128((__m128i*)(rgb_ptr2+48), rgb_4); \ SAVE_SI128((__m128i*)(rgb_ptr2+64), rgb_5); \ SAVE_SI128((__m128i*)(rgb_ptr2+80), rgb_6); \ void yuv420_rgb24_sse( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_load_si128 #define SAVE_SI128 _mm_stream_si128 const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-31); x+=32) { YUV2RGB_32 y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; rgb_ptr1+=96; rgb_ptr2+=96; } } #undef LOAD_SI128 #undef SAVE_SI128 } void yuv420_rgb24_sseu( uint32_t width, uint32_t height, const uint8_t *Y, const uint8_t *U, const uint8_t *V, uint32_t Y_stride, uint32_t UV_stride, uint8_t *RGB, uint32_t RGB_stride, YCbCrType yuv_type) { #define LOAD_SI128 _mm_loadu_si128 #define SAVE_SI128 _mm_storeu_si128 const YUV2RGBParam *const param = &(YUV2RGB[yuv_type]); uint32_t x, y; for(y=0; y<(height-1); y+=2) { const uint8_t *y_ptr1=Y+y*Y_stride, *y_ptr2=Y+(y+1)*Y_stride, *u_ptr=U+(y/2)*UV_stride, *v_ptr=V+(y/2)*UV_stride; uint8_t *rgb_ptr1=RGB+y*RGB_stride, *rgb_ptr2=RGB+(y+1)*RGB_stride; for(x=0; x<(width-31); x+=32) { YUV2RGB_32 y_ptr1+=32; y_ptr2+=32; u_ptr+=16; v_ptr+=16; rgb_ptr1+=96; rgb_ptr2+=96; } } #undef LOAD_SI128 #undef SAVE_SI128 } #endif //__SSE2__ ================================================ FILE: PinBoxTestProject/PinBoxTestProject/yuv_rgb.h ================================================ // Copyright 2016 Adrien Descamps // Distributed under BSD 3-Clause License // Provide optimized functions to convert images from 8bits yuv420 to rgb24 format // There are a few slightly different variations of the YCbCr color space with different parameters that // change the conversion matrix. // The three most common YCbCr color space, defined by BT.601, BT.709 and JPEG standard are implemented here. // See the respective standards for details // The matrix values used are derived from http://www.equasys.de/colorconversion.html // YUV420 is stored as three separate channels, with U and V (Cb and Cr) subsampled by a 2 factor // For conversion from yuv to rgb, no interpolation is done, and the same UV value are used for 4 rgb pixels. This // is suboptimal for image quality, but by far the fastest method. // For all methods, width and height should be even, if not, the last row/column of the result image won't be affected. // For sse methods, if the width if not divisable by 32, the last (width%32) pixels of each line won't be affected. #include typedef enum { YCBCR_JPEG, YCBCR_601, YCBCR_709 } YCbCrType; #ifdef __cplusplus extern "C" { #endif // yuv to rgb, standard c implementation void yuv420_rgb24_std( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // yuv to rgb, sse implementation // pointers must be 16 byte aligned, and strides must be divisable by 16 void yuv420_rgb24_sse( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // yuv to rgb, sse implementation // pointers do not need to be 16 byte aligned void yuv420_rgb24_sseu( uint32_t width, uint32_t height, const uint8_t *y, const uint8_t *u, const uint8_t *v, uint32_t y_stride, uint32_t uv_stride, uint8_t *rgb, uint32_t rgb_stride, YCbCrType yuv_type); // rgb to yuv, standard c implementation void rgb24_yuv420_std( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); // rgb to yuv, sse implementation // pointers must be 16 byte aligned, and strides must be divisible by 16 void rgb24_yuv420_sse( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); // rgb to yuv, sse implementation // pointers do not need to be 16 byte aligned void rgb24_yuv420_sseu( uint32_t width, uint32_t height, const uint8_t *rgb, uint32_t rgb_stride, uint8_t *y, uint8_t *u, uint8_t *v, uint32_t y_stride, uint32_t uv_stride, YCbCrType yuv_type); #ifdef __cplusplus } #endif ================================================ FILE: PinBoxTestProject/PinBoxTestProject.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PinBoxTestProject", "PinBoxTestProject\PinBoxTestProject.vcxproj", "{901BAB37-7D47-4095-9D2A-F203382FDA88}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {901BAB37-7D47-4095-9D2A-F203382FDA88}.Debug|x64.ActiveCfg = Debug|x64 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Debug|x64.Build.0 = Debug|x64 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Debug|x86.ActiveCfg = Debug|Win32 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Debug|x86.Build.0 = Debug|Win32 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Release|x64.ActiveCfg = Release|x64 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Release|x64.Build.0 = Release|x64 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Release|x86.ActiveCfg = Release|Win32 {901BAB37-7D47-4095-9D2A-F203382FDA88}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ [![N|Solid](https://cdn.discordapp.com/attachments/340110838947905538/398531319048699905/test.png)](https://github.com/namkazt/PinBox) Welcome to Pinbox! Pinbox is a homebrew application (Soon .cia) for the Nintendo 3DS that streams content from your Windows PC to the 3DS. Keep in mind, Pinbox is currenty in alpha, so bugs will occur! Contact Namkazt on the Pinbox Discord for help. https://discord.gg/CpNpMdG # Current Support - Streaming from Windows PC to a 3DS ( or over internet from VPS windows server ) - Audio support (MP2 encode/decode) - Hardware acceleration Y2R - Emulation Xbox 360 Controller for awesome game support ( by ViGEm ) - Support for Keyboard mapping with profile select from 3DS side - Realtime config from 3DS side #### Plans - Implement Qt UI for basic use - add Hub UI for fast access to game or app - Checker for wifi and sleepmode and other events relating to 3DS # Requirements to get Pinbox to run: * Visual C++ Redistributable for Visual Studio 2015 https://goo.gl/ijdZ1x - Xbox 360 Accessories Software 1.2 (contains the missing device drivers) https://goo.gl/xPK8qE - Make sure Windows is up to date with the latest security patches and updates - Install the Virtual Game pad Emulation Framework https://goo.gl/qcuVbp - Keep in mind: The requirements to Pinbox may change, please check the #how-to-setup section of The Pinbox Discord Server first. #### Notes - Enable firewall to allow port 1234 in and out (or disable the firewall when using the software and enable the firewall when done) - Make sure both devices are connected to Wifi - You do not have to type in port 1234, this will crash the app - If you are getting a black screen in Pinbox, open server.cfg in the Pinbox server directory and change monitor index to zero # Installation Tutorial Video (Thanks to @GameInCanada): https://www.youtube.com/watch?v=Q-R2cy-vBgY # Troubleshooting Please follow the instructions in the Pinbox Discord since the troubleshooting requirements are changing all the time and will be updated constantly. ## If you are having issues don't hesitate to ask for help on our official Discord channel! ## https://discord.gg/CpNpMdG ================================================ FILE: ThirdParty/FakeInput/LICENSE ================================================ MIT license ----------- Copyright (C) 2011 by Richard Jedlicka Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: ThirdParty/FakeInput/src/actions/action.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_ACTION_HPP #define FI_ACTION_HPP namespace FakeInput { /** Abstract class representing arbitrary action which can be sent. */ class Action { public: /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ virtual Action* clone() const = 0; /** Performs the action. */ virtual void send() const = 0; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/actions/actions.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "actionsequence.hpp" #include "commandaction.hpp" #include "keyaction.hpp" #include "mouseaction.hpp" #include "waitaction.hpp" ================================================ FILE: ThirdParty/FakeInput/src/actions/actionsequence.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "actionsequence.hpp" #include namespace FakeInput { ActionSequence::ActionSequence() { } ActionSequence::ActionSequence(const ActionSequence& anotherSequence) { ActionList::const_iterator it; for(it = anotherSequence.actions_.begin(); it != anotherSequence.actions_.end(); ++it) { actions_.push_back((*it)->clone()); } } ActionSequence::~ActionSequence() { ActionList::iterator it; for(it = actions_.begin(); it != actions_.end(); ++it) { delete (*it); } } Action* ActionSequence::clone() const { return new ActionSequence(*this); } ActionSequence& ActionSequence::join(ActionSequence& anotherSequence) { actions_.push_back(anotherSequence.clone()); return *this; } ActionSequence& ActionSequence::press(Key key) { actions_.push_back(new KeyboardPress(key)); return *this; } ActionSequence& ActionSequence::press(KeyType type) { actions_.push_back(new KeyboardPress(type)); return *this; } ActionSequence& ActionSequence::press(MouseButton button) { actions_.push_back(new MousePress(button)); return *this; } ActionSequence& ActionSequence::release(Key key) { actions_.push_back(new KeyboardRelease(key)); return *this; } ActionSequence& ActionSequence::release(KeyType type) { actions_.push_back(new KeyboardRelease(type)); return *this; } ActionSequence& ActionSequence::release(MouseButton button) { actions_.push_back(new MouseRelease(button)); return *this; } ActionSequence& ActionSequence::moveMouse(int dx, int dy) { actions_.push_back(new MouseRelativeMotion(dx, dy)); return *this; } ActionSequence& ActionSequence::moveMouseTo(int x, int y) { actions_.push_back(new MouseAbsoluteMotion(x, y)); return *this; } ActionSequence& ActionSequence::wheelUp() { actions_.push_back(new MouseWheelUp()); return *this; } ActionSequence& ActionSequence::wheelDown() { actions_.push_back(new MouseWheelDown()); return *this; } ActionSequence& ActionSequence::runCommand(const std::string& cmd) { actions_.push_back(new CommandRun(cmd)); return *this; } ActionSequence& ActionSequence::wait(unsigned int milisec) { actions_.push_back(new Wait(milisec)); return *this; } void ActionSequence::send() const { ActionList::const_iterator it; for(it = actions_.begin(); it != actions_.end(); ++it) { (*it)->send(); } } } ================================================ FILE: ThirdParty/FakeInput/src/actions/actionsequence.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_ACTIONSEQUENCE_HPP #define FI_ACTIONSEQUENCE_HPP #include "action.hpp" #include "keyaction.hpp" #include "mouseaction.hpp" #include "commandaction.hpp" #include "waitaction.hpp" #include namespace FakeInput { /** Represents a sequence of actions. */ class ActionSequence : public Action { typedef std::list ActionList; public: /** ActionSequence constructor. */ ActionSequence(); /** ActionSequence copy-constructor. */ ActionSequence(const ActionSequence& anotherSequence); /** ActionSequence destructor. */ virtual ~ActionSequence(); /** Creates new copy of this action sequence. * * @returns * New copy of this action sequence allocated on heap. */ Action* clone() const; /** Adds another sequence to the end of this sequence. * * So all actions from another sequence will be performed * after all action before it in this sequence * * @param anotherSequence * Another sequence to join * * @returns * The referece to this action */ ActionSequence& join(ActionSequence& anotherSequence); /** Adds key press action to the end of this sequence. * * @param key * The key to press * * @returns * The referece to this action */ ActionSequence& press(Key key); /** Adds key press action to the end of this sequence. * * @param keyType * The keyType of key to press * * @returns * The referece to this action */ ActionSequence& press(KeyType keyType); /** Adds mouse press action to the end of this sequence. * * @param button * The mouse button to press * * @returns * The referece to this action */ ActionSequence& press(MouseButton button); /** Adds key release action to the end of this sequence. * * @param key * The key to release * * @returns * The referece to this action */ ActionSequence& release(Key key); /** Adds key release action to the end of this sequence. * * @param keyType * The keyType of key to release * * @returns * The referece to this action */ ActionSequence& release(KeyType keyType); /** Adds mouse release action to the end of this sequence. * * @param button * The mouse button to release * * @returns * The referece to this action */ ActionSequence& release(MouseButton button); /** Adds mouse relative motion action to the end of this sequence. * * @param dx * Amount of pixels to move on X axis * @param dy * Amount of pixels to move on Y axis * * @returns * The referece to this action */ ActionSequence& moveMouse(int dx, int dy); /** Adds mouse absolute motion action to the end of this sequence. * * @param x * Where to move on X axis * @param y * Where to move on Y axis * * @returns * The referece to this action */ ActionSequence& moveMouseTo(int x, int y); /** Adds mouse wheel up action to the end of this sequence. * * @returns * The referece to this action */ ActionSequence& wheelUp(); /** Adds mouse wheel down action to the end of this sequence. * * @returns * The referece to this action */ ActionSequence& wheelDown(); /** Adds command run action to the end of this sequence. * * @param cmd * Command to run * * @returns * The referece to this action */ ActionSequence& runCommand(const std::string& cmd); /** Adds wait action to the end of this sequence. * * @param milisec * Time to wait in milisecods * * @returns * The referece to this action */ ActionSequence& wait(unsigned int milisec); /** Performs all actions in sequence. */ void send() const; private: /** List of actions in this sequence. */ ActionList actions_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/actions/commandaction.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "commandaction.hpp" #include "system.hpp" namespace FakeInput { CommandRun::CommandRun(const std::string& cmd): cmd_(cmd) { } Action* CommandRun::clone() const { return new CommandRun(cmd_); } void CommandRun::send() const { System::run(cmd_); } } ================================================ FILE: ThirdParty/FakeInput/src/actions/commandaction.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_COMMANDACTION_HPP #define FI_COMMANDACTION_HPP #include #include "action.hpp" namespace FakeInput { /** Represents a command run action. * * Runs a specified command-line command. */ class CommandRun : public Action { public: /** CommandRun action constructor. * * @param cmd * Command to run. */ CommandRun(const std::string& cmd); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: /** Command to run. */ std::string cmd_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/actions/keyaction.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "keyaction.hpp" #include "keyboard.hpp" namespace FakeInput { KeyAction::KeyAction(KeyActionCallback callback, Key key): callback_(callback), key_(key) { } Action* KeyAction::clone() const { return new KeyAction(callback_, key_); } void KeyAction::send() const { callback_(key_); } KeyboardPress::KeyboardPress(Key key): KeyAction(Keyboard::pressKey, key) { } KeyboardPress::KeyboardPress(KeyType keyType): KeyAction(Keyboard::pressKey, Key(keyType)) { } KeyboardRelease::KeyboardRelease(Key key): KeyAction(Keyboard::releaseKey, key) { } KeyboardRelease::KeyboardRelease(KeyType keyType): KeyAction(Keyboard::releaseKey, Key(keyType)) { } } ================================================ FILE: ThirdParty/FakeInput/src/actions/keyaction.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEYACTION_HPP #define FI_KEYACTION_HPP #include "action.hpp" #include "key.hpp" namespace FakeInput { typedef void (*KeyActionCallback) (Key key); /** Represent a key action. */ class KeyAction : public Action { public: /** KeyAction constructor. * * @param callback * Callback whitch can handle with key. * @param key * Key to be handled. */ KeyAction(KeyActionCallback callback, Key key); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: KeyActionCallback callback_; Key key_; }; /** Represent a key press action. */ class KeyboardPress : public KeyAction { public: /** KeyboardPress action constructor. * * @param key * Key to be pressed. */ KeyboardPress(Key key); /** KeyboardPress action constructor. * * @param keyType * Type of key to be pressed. */ KeyboardPress(KeyType keyType); }; /** Represent a key release action. */ class KeyboardRelease : public KeyAction { public: /** KeyboardRelease action constructor. * * @param key * Key to be released. */ KeyboardRelease(Key key); /** KeyboardRelease action constructor. * * @param keyType * Type of key to be released. */ KeyboardRelease(KeyType keyType); }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/actions/mouseaction.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mouseaction.hpp" namespace FakeInput { // -------- MOUSE BUTTONS --------- // MouseButtonAction::MouseButtonAction(MouseButtonActionCallback callback, MouseButton button): callback_(callback), button_(button) { } Action* MouseButtonAction::clone() const { return new MouseButtonAction(callback_, button_); } void MouseButtonAction::send() const { (*callback_)(button_); } MousePress::MousePress(MouseButton button): MouseButtonAction(Mouse::pressButton, button) { } MouseRelease::MouseRelease(MouseButton button): MouseButtonAction(Mouse::releaseButton, button) { } // -------- MOUSE MOTION --------- // MouseMotionAction::MouseMotionAction(MouseMotionActionCallback callback, int x, int y): callback_(callback), x_(x), y_(y) { } Action* MouseMotionAction::clone() const { return new MouseMotionAction(callback_, x_, y_); } void MouseMotionAction::send() const { callback_(x_, y_); } MouseRelativeMotion::MouseRelativeMotion(int dx, int dy): MouseMotionAction(Mouse::move, dx, dy) { } MouseAbsoluteMotion::MouseAbsoluteMotion(int x, int y): MouseMotionAction(Mouse::moveTo, x, y) { } // -------- MOUSE WHEEL --------- // MouseWheelAction::MouseWheelAction(MouseWheelActionCallback callback): callback_(callback) { } Action* MouseWheelAction::clone() const { return new MouseWheelAction(callback_); } void MouseWheelAction::send() const { callback_(); } MouseWheelUp::MouseWheelUp(): MouseWheelAction(Mouse::wheelUp) { } MouseWheelDown::MouseWheelDown(): MouseWheelAction(Mouse::wheelDown) { } } ================================================ FILE: ThirdParty/FakeInput/src/actions/mouseaction.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_MOUSEACTION_HPP #define FI_MOUSEACTION_HPP #include "action.hpp" #include "mouse.hpp" namespace FakeInput { // -------- MOUSE BUTTONS --------- // typedef void (*MouseButtonActionCallback)(MouseButton button); /** Represents mouse button action. */ class MouseButtonAction : public Action { public: /** MouseButtonAction constructor. * * @param callback * Callback which can handle with mouse button. * @param button * Mouse button to be handled. */ MouseButtonAction(MouseButtonActionCallback callback, MouseButton button); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: MouseButtonActionCallback callback_; MouseButton button_; }; /** Represents mouse button press action. */ class MousePress : public MouseButtonAction { public: /** MousePress action constructor. * * @param button * Mouse button to press. */ MousePress(MouseButton button); }; /** Represents mouse button release action. */ class MouseRelease : public MouseButtonAction { public: /** MouseRelease action constructor. * * @param button * Mouse button to release. */ MouseRelease(MouseButton button); }; // -------- MOUSE MOTION --------- // typedef void (*MouseMotionActionCallback)(int x, int y); /** Represents mouse motion action. */ class MouseMotionAction : public Action { public: /** MouseButtonAction constructor. * * @param callback * Callback which can move mouse. * @param x * How to operate on X axis. * @param y * How to operate on Y axis. */ MouseMotionAction(MouseMotionActionCallback callback, int x, int y); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: MouseMotionActionCallback callback_; int x_; int y_; }; /** Represents mouse relative motion action. * * Relative means to move mouse some amount of pixels in some direction. */ class MouseRelativeMotion : public MouseMotionAction { public: /** MouseAbsoluteMotion constructor. * * @param dx * Amount of pixels to move on X axis. * @param dy * Amount of pixels to move on Y axis. */ MouseRelativeMotion(int dx, int dy); }; /** Represents mouse absolute motion action. * * Absolute means to move mouse on the specified position. */ class MouseAbsoluteMotion : public MouseMotionAction { public: /** MouseAbsoluteMotion constructor. * * @param x * Position on X axis to move on. * @param y * Position on Y axis to move on. */ MouseAbsoluteMotion(int x, int y); }; // -------- MOUSE WHEEL --------- // typedef void (*MouseWheelActionCallback)(); class MouseWheelAction : public Action { public: /** MouseWheelAction constructor. * * @param callback * Callback which can handle with mouse wheel. */ MouseWheelAction(MouseWheelActionCallback callback); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: MouseWheelActionCallback callback_; }; /** Represents mouse wheel up rotation action. */ class MouseWheelUp : public MouseWheelAction { public: /** MouseWheelUp action constructor. */ MouseWheelUp(); }; /** Represents mouse wheel down rotation action. */ class MouseWheelDown : public MouseWheelAction { public: /** MouseWheelDown action constructor. */ MouseWheelDown(); }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/actions/waitaction.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "waitaction.hpp" #include "system.hpp" namespace FakeInput { Wait::Wait(unsigned int milisec): milisec_(milisec) { } Action* Wait::clone() const { return new Wait(milisec_); } void Wait::send() const { System::wait(milisec_); } } ================================================ FILE: ThirdParty/FakeInput/src/actions/waitaction.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_WAITACTION_HPP #define FI_WAITACTION_HPP #include "action.hpp" namespace FakeInput { /** Represents a wait action. * * Waits specified amount of time in miliseconds. */ class Wait : public Action { public: /** Wait action constructor. * * @param milisec * Amount of time to wait in miliseconds. */ Wait(unsigned int milisec); /** Creates new copy of this action. * * @returns * New copy of this action allocated on heap. */ Action* clone() const; /** Performs this action. */ void send() const; private: unsigned int milisec_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/config.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef WC_CONFIG_HPP #define WC_CONFIG_HPP /* #undef TEST_APP */ #ifndef UNIX /* #undef UNIX */ #endif #ifndef WIN32 #define WIN32 #endif #endif ================================================ FILE: ThirdParty/FakeInput/src/config.hpp.cmake ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef WC_CONFIG_HPP #define WC_CONFIG_HPP #cmakedefine TEST_APP #ifndef UNIX #cmakedefine UNIX #endif #ifndef WIN32 #cmakedefine WIN32 #endif #endif ================================================ FILE: ThirdParty/FakeInput/src/display_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "display_unix.hpp" namespace FakeInput { Display* display() { static Display* display = XOpenDisplay(0); return display; } } ================================================ FILE: ThirdParty/FakeInput/src/display_unix.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_DISPLAY_UNIX_HPP #define FI_DISPLAY_UNIX_HPP #include "config.hpp" #include namespace FakeInput { /** Get connection to the X server * * @warning @image html tux.png * Unix-like platform only */ Display* display(); } #endif ================================================ FILE: ThirdParty/FakeInput/src/fakeinput.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // include core #include "keyboard.hpp" #include "mouse.hpp" #include "system.hpp" ================================================ FILE: ThirdParty/FakeInput/src/key.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEY_HPP #define FI_KEY_HPP #include "config.hpp" #ifdef UNIX #include "key_unix.hpp" #elif WIN32 #include "key_win.hpp" #endif namespace FakeInput { #ifdef UNIX /** Class representing a real key. * * @image html tux.png * On Unix-like platform derived from Key_unix */ typedef Key_unix Key; #elif WIN32 /** * @image html windows.png * On Windows derived from Key_win */ typedef Key_win Key; #endif } #endif ================================================ FILE: ThirdParty/FakeInput/src/key_base.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "key_base.hpp" #include #include namespace FakeInput { Key_base::Key_base() { code_ = 0; name_ = ""; } unsigned int Key_base::code() const { return code_; } const std::string& Key_base::name() const { return name_; } } ================================================ FILE: ThirdParty/FakeInput/src/key_base.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEY_BASE_HPP #define FI_KEY_BASE_HPP #include "config.hpp" #include namespace FakeInput { /** Represents real keyboard button. */ class Key_base { public: /** Gives the hardware code of the key. * * @returns * Device dependend code of the key. */ virtual unsigned int code() const; /** Gives the name of the key. * * @returns * The name of the key. */ virtual const std::string& name() const; protected: /** Key_base constructor. * * Creates key representing no real key. */ Key_base(); unsigned int code_; std::string name_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/key_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "key_unix.hpp" #include #include #include "display_unix.hpp" #include "mapper.hpp" namespace FakeInput { Key_unix::Key_unix() { keysym_ = 0; } Key_unix::Key_unix(KeyType type) { if(type == Key_NoKey) { keysym_ = 0; code_ = 0; name_ = ""; } else { keysym_ = translateKey(type); code_ = XKeysymToKeycode(display(), keysym_); name_ = XKeysymToString(keysym_); } } Key_unix::Key_unix(XEvent* event): Key_base() { if(event->type != KeyPress && event->type != KeyRelease) throw std::logic_error("Cannot get key from non-key event"); code_ = event->xkey.keycode; keysym_ = XKeycodeToKeysym(event->xkey.display, code_, 0); name_ = XKeysymToString(keysym_); } Key_unix::Key_unix(KeySym keysym): Key_base() { code_ = XKeysymToKeycode(display(), keysym); keysym_ = keysym; name_ = XKeysymToString(keysym); } KeySym Key_unix::keysym() const { return keysym_; } } ================================================ FILE: ThirdParty/FakeInput/src/key_unix.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEY_UNIX_HPP #define FI_KEY_UNIX_HPP #include "config.hpp" #include #include #include "key_base.hpp" #include "types.hpp" namespace FakeInput { /** Represents real keyboard button with appropriate methods on Unix-like platform. * * @warning @image html tux.png * Unix-like platform only */ class Key_unix : public Key_base { public: /** Key constructor. * * Creates key representing no real key. */ Key_unix(); /** Key constructor * * Creates key according to the key type * * @param type * KeyType to be created * * @note @image html note.png * There is no quarantee the key type will act as you expected, * it depends on keyboard layout, language etc., e.g. on Czech * keyboard the @em Key_2 key will print @em 2 or @em ě according to * the set keyboard layout (US or Czech) * * @note * If there is not appropriate key type, you can use platform dependend * methods Key::fromKeySym (unix) and Key::fromVirtualKey (win) */ Key_unix(KeyType type); /** Key contructor * * Creates key from keycode from given X key event. * * @param event * XKeyEvent (Xlib key event) containing keycode. * * @warning @image html tux.png * Unix-like platform only */ Key_unix(XEvent* event); /** Key contructor * * Creates key from the KeySym. * * @param keySym * The KeySym representing appropriate key. * KeySyms can be obtained from X11/keysymdef.h * file in Xlib sources * * @warning @image html tux.png * Unix-like platform only. */ Key_unix(KeySym keySym); /** Gives the KeySym representing the key. * * @returns * KeySym representing the key. * * @warning @image html tux.png * Unix-like platform only */ KeySym keysym() const; private: KeySym keysym_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/key_win.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "key_win.hpp" #include #include #include "mapper.hpp" namespace FakeInput { Key_win::Key_win() { virtualKey_ = 0; } Key_win::Key_win(KeyType type) { if(type == Key_NoKey) { virtualKey_ = 0; code_ = 0; name_ = ""; } else { virtualKey_ = (WORD) translateKey(type); Key_win tmpKey(virtualKey_); code_ = tmpKey.code_; name_ = tmpKey.name_; } } Key_win::Key_win(MSG* message) { switch(message->message) { case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: virtualKey_ = message->wParam; break; default: std::logic_error("Cannot get key from non-key message"); break; } Key_win tmpKey(virtualKey_); code_ = tmpKey.code_; name_ = tmpKey.name_; } Key_win::Key_win(WORD virtualKey): virtualKey_(virtualKey) { code_ = MapVirtualKey(virtualKey, MAPVK_VK_TO_VSC); LONG lParam = code_; switch (virtualKey) { case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: // arrow keys case VK_PRIOR: case VK_NEXT: // page up and page down case VK_END: case VK_HOME: case VK_INSERT: case VK_DELETE: case VK_DIVIDE: // numpad slash case VK_NUMLOCK: { lParam |= 0x100; // set extended bit break; } } char name[128]; if(GetKeyNameText(lParam << 16, name, 128)) { name_ = std::string(name); } else { std::cerr << "Cannot get key name"; name_ = ""; } } WORD Key_win::virtualKey() const { return virtualKey_; } } ================================================ FILE: ThirdParty/FakeInput/src/key_win.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEY_WIN_HPP #define FI_KEY_WIN_HPP #include "config.hpp" #include #include #include "key_base.hpp" #include "types.hpp" namespace FakeInput { /** Represents real keyboard button with appropriate methods on Windows. * * @warning @image html windows.png * Windows platform only. */ class Key_win : public Key_base { public: /** Key constructor. * * Creates key representing no real key. */ Key_win(); /** Key constructor * * Creates key according to the key type * * @param type * KeyType to be created * * @note @image html note.png * There is no quarantee the key type will act as you expected, * it depends on keyboard layout, language etc., e.g. on Czech * keyboard the @em Key_2 key will print @em 2 or @em ě according to * the set keyboard layout (US or Czech) * * @note * If there is not appropriate key type, you can use platform dependend * methods Key::fromKeySym (unix) and Key::fromVirtualKey (win) */ Key_win(KeyType type); /** Key constructor * * Creates key from virtual-key code from given Windows key message. * * @param message * Windows WM_[SYS]KEY(DOWN|UP) message containing virtual-key code. * * @warning @image html windows.png * Windows platform only */ Key_win(MSG* message); /** Key constructor * * Creates key from the name of the virtual key. * * @param virtualKey * The virtual-key code. * Virtual-key codes can be obtained from winuser.h header file * or http://msdn.microsoft.com/en-us/library/dd375731 . * * @warning @image html windows.png * Windows platform only. */ Key_win(WORD virtualKey); /** Gives the virtual-key code representing the key. * * @returns * virtual-key code representing the key. * * @warning @image html windows.png * Windows platform only. */ WORD virtualKey() const; private: WORD virtualKey_; }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/keyboard.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "keyboard.hpp" namespace FakeInput { void Keyboard::pressKey(Key key) { sendKeyEvent_(key, true); } void Keyboard::releaseKey(Key key) { sendKeyEvent_(key, false); } } ================================================ FILE: ThirdParty/FakeInput/src/keyboard.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_KEYBOARD_HPP #define FI_KEYBOARD_HPP #include "config.hpp" #include "key.hpp" namespace FakeInput { /** Represents keyboard device. * * Allows you to simulate key press. */ class Keyboard { public: /** Simulate key press. * * @param key * Key object representing real key to be pressed. */ static void pressKey(Key key); /** Simulate key release * * @param key * Key object representing real key to be released. */ static void releaseKey(Key key); private: /** Send fake key event to the system. * * @param key * Key object representing real key to be pressed. * @param isPress * Whether event is press or release. */ static void sendKeyEvent_(Key key, bool isPress); }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/keyboard_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "keyboard.hpp" #include #include #include "display_unix.hpp" #include namespace FakeInput { void Keyboard::sendKeyEvent_(Key key, bool isPress) { if(key.keysym() == NoSymbol) { std::cerr << "Cannot send event" << std::endl; } else { XTestFakeKeyEvent(display(), key.code(), isPress, CurrentTime); XFlush(display()); } } } ================================================ FILE: ThirdParty/FakeInput/src/keyboard_win.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "keyboard.hpp" #include #include namespace FakeInput { void Keyboard::sendKeyEvent_(Key key, bool isPress) { if(key.code() == 0) { std::cerr << "Cannot send event" << std::endl; } else { INPUT input; ZeroMemory(&input, sizeof(INPUT)); input.type = INPUT_KEYBOARD; input.ki.wVk = key.virtualKey(); input.ki.dwFlags = (isPress) ? 0 : KEYEVENTF_KEYUP; SendInput(1, &input, sizeof(INPUT)); } } } ================================================ FILE: ThirdParty/FakeInput/src/mapper.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_MAPPER_HPP #define FI_MAPPER_HPP #include "mouse.hpp" #include "key.hpp" namespace FakeInput { /** Translates MouseButton to the platform's representation of the button. */ long translateMouseButton(MouseButton button); /** Translates KeyType to the platform's representation of the key. */ unsigned long translateKey(KeyType key); } #endif ================================================ FILE: ThirdParty/FakeInput/src/mapper_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mapper.hpp" #include #include namespace FakeInput { static long buttonTable[] = { Button1, // Mouse::LEFT Button2, // Mouse::MIDDLE Button3 // Mouse::RIGHT }; static long keyTable[] = { XK_A, XK_B, XK_C, XK_D, XK_E, XK_F, XK_G, XK_H, XK_I, XK_J, XK_K, XK_L, XK_M, XK_N, XK_O, XK_P, XK_Q, XK_R, XK_S, XK_T, XK_U, XK_V, XK_W, XK_X, XK_Y, XK_Z, XK_0, XK_1, XK_2, XK_3, XK_4, XK_5, XK_6, XK_7, XK_8, XK_9, XK_F1, XK_F2, XK_F3, XK_F4, XK_F5, XK_F6, XK_F7, XK_F8, XK_F9, XK_F10, XK_F11, XK_F12, XK_F13, XK_F14, XK_F15, XK_F16, XK_F17, XK_F18, XK_F19, XK_F20, XK_F21, XK_F22, XK_F23, XK_F24, XK_Escape, XK_space, XK_Return, XK_BackSpace, XK_Tab, XK_Shift_L, XK_Shift_R, XK_Control_L, XK_Control_R, XK_Alt_L, XK_Alt_R, XK_Super_L, XK_Super_R, XK_Menu, XK_Caps_Lock, XK_Num_Lock, XK_Scroll_Lock, XK_Print, XK_Pause, XK_Insert, XK_Delete, XK_Prior, XK_Next, XK_Home, XK_End, XK_Left, XK_Up, XK_Right, XK_Down, XK_KP_0, XK_KP_1, XK_KP_2, XK_KP_3, XK_KP_4, XK_KP_5, XK_KP_6, XK_KP_7, XK_KP_8, XK_KP_9, XK_KP_Add, XK_KP_Subtract, XK_KP_Multiply, XK_KP_Divide, XK_KP_Decimal, XK_KP_Enter }; long translateMouseButton(MouseButton button) { return buttonTable[button]; } unsigned long translateKey(KeyType key) { return keyTable[key]; } } ================================================ FILE: ThirdParty/FakeInput/src/mapper_win.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mapper.hpp" #include namespace FakeInput { static long buttonTable[] = { MOUSEEVENTF_LEFTDOWN, // Mouse::LEFT MOUSEEVENTF_MIDDLEDOWN, // Mouse::MIDDLE MOUSEEVENTF_RIGHTDOWN // Mouse::RIGHT }; static long keyTable[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, // A - I 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, // J - R 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, // S - Z 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, // 0 - 9 VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18, VK_F19, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24, VK_ESCAPE, VK_SPACE, VK_RETURN, VK_BACK, VK_TAB, VK_LSHIFT, VK_RSHIFT, VK_LCONTROL, VK_RCONTROL, VK_LMENU, VK_RMENU, VK_LWIN, VK_RWIN, VK_APPS, VK_CAPITAL, VK_NUMLOCK, VK_SCROLL, VK_SNAPSHOT, VK_PAUSE, VK_INSERT, VK_DELETE, VK_PRIOR, VK_NEXT, VK_HOME, VK_END, VK_LEFT, VK_UP, VK_RIGHT, VK_DOWN, VK_NUMPAD0, VK_NUMPAD1, VK_NUMPAD2, VK_NUMPAD3, VK_NUMPAD4, VK_NUMPAD5, VK_NUMPAD6, VK_NUMPAD7, VK_NUMPAD8, VK_NUMPAD9, VK_ADD, VK_SUBTRACT, VK_MULTIPLY, VK_DIVIDE, VK_DECIMAL, VK_RETURN }; long translateMouseButton(MouseButton button) { return buttonTable[button]; } unsigned long translateKey(KeyType key) { return keyTable[key]; } } ================================================ FILE: ThirdParty/FakeInput/src/mouse.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_MOUSE_HPP #define FI_MOUSE_HPP #include "config.hpp" #include "types.hpp" namespace FakeInput { /** Represents mouse device. * * Allows you to move the cursor to the required position. * Or simulate mouse button press. */ class Mouse { public: /** Moves mouse cursor in direction. * * @param xDirection * Direction in pixels on X-axis. * @param yDirection * Direction in pixels on Y-axis. */ static void move(int xDirection, int yDirection); /** Moves mouse cursor to the specified position. * * @param x * X coordinate of the position. * @param y * Y coordinate of the position. */ static void moveTo(int x, int y); /** Simulates mouse button press. * * @param button * MouseButton to be pressed */ static void pressButton(MouseButton button); /** Simulates mouse button release. * * @param button * MouseButton to be released */ static void releaseButton(MouseButton button); /** Simulates wheel up move */ static void wheelUp(); /** Simulates wheel up down */ static void wheelDown(); }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/mouse_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mouse.hpp" #include #include #include "display_unix.hpp" #include "mapper.hpp" namespace FakeInput { void Mouse::move(int x, int y) { XTestFakeRelativeMotionEvent(display(), x, y, CurrentTime); XFlush(display()); } void Mouse::moveTo(int x, int y) { XTestFakeMotionEvent(display(), -1, x, y, CurrentTime); XFlush(display()); } void Mouse::pressButton(MouseButton button) { int xButton = translateMouseButton(button); XTestFakeButtonEvent(display(), xButton, true, CurrentTime); XFlush(display()); } void Mouse::releaseButton(MouseButton button) { int xButton = translateMouseButton(button); XTestFakeButtonEvent(display(), xButton, false, CurrentTime); XFlush(display()); } void Mouse::wheelUp() { XTestFakeButtonEvent(display(), 4, true, CurrentTime); XSync(display(), false); XTestFakeButtonEvent(display(), 4, false, CurrentTime); XFlush(display()); } void Mouse::wheelDown() { XTestFakeButtonEvent(display(), 5, true, CurrentTime); XSync(display(), false); XTestFakeButtonEvent(display(), 5, false, CurrentTime); XFlush(display()); } } ================================================ FILE: ThirdParty/FakeInput/src/mouse_win.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "mouse.hpp" #include #include "mapper.hpp" #include "types.hpp" #define INIT_INPUT(var) \ INPUT var; \ ZeroMemory(&var, sizeof(INPUT)); \ var.type = INPUT_MOUSE; namespace FakeInput { void Mouse::move(int x, int y) { INIT_INPUT(input); input.mi.dx = x; input.mi.dy = y; input.mi.dwFlags = MOUSEEVENTF_MOVE; SendInput(1, &input, sizeof(INPUT)); } void Mouse::moveTo(int x, int y) { double screenWidth = GetSystemMetrics(SM_CXSCREEN) - 1; double screenHeight = GetSystemMetrics(SM_CYSCREEN) - 1; double fx = x * (65535.0f / screenWidth); double fy = y * (65535.0f / screenHeight); INIT_INPUT(input); input.mi.dx = (LONG) fx; input.mi.dy = (LONG) fy; input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; SendInput(1, &input, sizeof(INPUT)); } void Mouse::pressButton(MouseButton button) { INIT_INPUT(input); input.mi.dwFlags = translateMouseButton(button); SendInput(1, &input, sizeof(INPUT)); } void Mouse::releaseButton(MouseButton button) { INIT_INPUT(input); input.mi.dwFlags = translateMouseButton(button) << 1; SendInput(1, &input, sizeof(INPUT)); } void Mouse::wheelUp() { INIT_INPUT(input); input.mi.dwFlags = MOUSEEVENTF_WHEEL; input.mi.mouseData = WHEEL_DELTA; SendInput(1, &input, sizeof(INPUT)); } void Mouse::wheelDown() { INIT_INPUT(input); input.mi.dwFlags = MOUSEEVENTF_WHEEL; input.mi.mouseData = -WHEEL_DELTA; SendInput(1, &input, sizeof(INPUT)); } } ================================================ FILE: ThirdParty/FakeInput/src/system.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_SYSTEM_HPP #define FI_SYSTEM_HPP #include "config.hpp" #include namespace FakeInput { /** Handler of some system operations. * * Allows you to run command-line commands * and wait for specified time */ class System { public: /** Executes command-line command. * * @param cmd * %Command to run. */ static void run(const std::string& cmd); /** Sleeps the current thread and wait for specified time. * * @param milisec * time to wait in miliseconds */ static void wait(unsigned int milisec); }; } #endif ================================================ FILE: ThirdParty/FakeInput/src/system_unix.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "system.hpp" #include #include namespace FakeInput { void System::run(const std::string& cmd) { std::string command = cmd + " &"; system(command.c_str()); } void System::wait(unsigned int milisec) { timespec tm; tm.tv_sec = milisec / 1000; tm.tv_nsec = (milisec % 1000) * 1000000; nanosleep(&tm, NULL); } } ================================================ FILE: ThirdParty/FakeInput/src/system_win.cpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "system.hpp" #include #include namespace FakeInput { void System::run(const std::string& cmd) { std::string command = "start " + cmd; system(command.c_str()); } void System::wait(unsigned int milisec) { Sleep(milisec); } } ================================================ FILE: ThirdParty/FakeInput/src/types.hpp ================================================ /** * This file is part of the FakeInput library (https://github.com/uiii/FakeInput) * * Copyright (C) 2011 by Richard Jedlicka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef FI_TYPES_HPP #define FI_TYPES_HPP namespace FakeInput { /** Mouse button which can be pressed or released */ enum MouseButton { Mouse_Left, Mouse_Middle, Mouse_Right }; /** Predefined common US keyboard layout key types */ enum KeyType { Key_NoKey = -1, Key_A, Key_B, Key_C, Key_D, Key_E, Key_F, Key_G, Key_H, Key_I, Key_J, Key_K, Key_L, Key_M, Key_N, Key_O, Key_P, Key_Q, Key_R, Key_S, Key_T, Key_U, Key_V, Key_W, Key_X, Key_Y, Key_Z, Key_0, Key_1, Key_2, Key_3, Key_4, Key_5, Key_6, Key_7, Key_8, Key_9, Key_F1, Key_F2, Key_F3, Key_F4, Key_F5, Key_F6, Key_F7, Key_F8, Key_F9, Key_F10, Key_F11, Key_F12, Key_F13, Key_F14, Key_F15, Key_F16, Key_F17, Key_F18, Key_F19, Key_F20, Key_F21, Key_F22, Key_F23, Key_F24, Key_Escape, Key_Space, Key_Return, Key_Backspace, Key_Tab, Key_Shift_L, Key_Shift_R, Key_Control_L, Key_Control_R, Key_Alt_L, Key_Alt_R, Key_Win_L, Key_Win_R, Key_Apps, Key_CapsLock, Key_NumLock, Key_ScrollLock, Key_PrintScreen, Key_Pause, Key_Insert, Key_Delete, Key_PageUP, Key_PageDown, Key_Home, Key_End, Key_Left, Key_Right, Key_Up, Key_Down, Key_Numpad0, Key_Numpad1, Key_Numpad2, Key_Numpad3, Key_Numpad4, Key_Numpad5, Key_Numpad6, Key_Numpad7, Key_Numpad8, Key_Numpad9, Key_NumpadAdd, Key_NumpadSubtract, Key_NumpadMultiply, Key_NumpadDivide, Key_NumpadDecimal, Key_NumpadEnter }; } #endif ================================================ FILE: ThirdParty/ViGEm/Include/ViGEmBusDriver.h ================================================ /* MIT License Copyright (c) 2016 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // {A77BC4D5-6AF7-4E69-8DC4-6B88A6028CE6} // ReSharper disable once CppMissingIncludeGuard DEFINE_GUID(GUID_VIGEM_INTERFACE_PDO, 0xA77BC4D5, 0x6AF7, 0x4E69, 0x8D, 0xC4, 0x6B, 0x88, 0xA6, 0x02, 0x8C, 0xE6); // {A8BA2D1F-894F-464A-B0CE-7A0C8FD65DF1} DEFINE_GUID(GUID_DEVCLASS_VIGEM_RAWPDO, 0xA8BA2D1F, 0x894F, 0x464A, 0xB0, 0xCE, 0x7A, 0x0C, 0x8F, 0xD6, 0x5D, 0xF1); #pragma once // // Describes the current stage a PDO completed // typedef enum _VIGEM_PDO_STAGE { ViGEmPdoCreate, ViGEmPdoPrepareHardware, ViGEmPdoInternalIoControl } VIGEM_PDO_STAGE, *PVIGEM_PDO_STAGE; // // PDO stage result callback definition // typedef VOID (*PVIGEM_BUS_PDO_STAGE_RESULT)( _In_ PINTERFACE InterfaceHeader, _In_ VIGEM_PDO_STAGE Stage, _In_ ULONG Serial, _In_ NTSTATUS Status ); typedef struct _VIGEM_BUS_INTERFACE { // // Standard interface header, must be present // INTERFACE InterfaceHeader; // // PDO stage result callback // PVIGEM_BUS_PDO_STAGE_RESULT BusPdoStageResult; } VIGEM_BUS_INTERFACE, *PVIGEM_BUS_INTERFACE; #define VIGEM_BUS_INTERFACE_VERSION 1 VOID FORCEINLINE BUS_PDO_REPORT_STAGE_RESULT( VIGEM_BUS_INTERFACE Interface, VIGEM_PDO_STAGE Stage, ULONG Serial, NTSTATUS Status ) { (*Interface.BusPdoStageResult)(&Interface.InterfaceHeader, Stage, Serial, Status); } ================================================ FILE: ThirdParty/ViGEm/Include/ViGEmBusShared.h ================================================ /* MIT License Copyright (c) 2016 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // {96E42B22-F5E9-42F8-B043-ED0F932F014F} // ReSharper disable once CppMissingIncludeGuard DEFINE_GUID(GUID_DEVINTERFACE_BUSENUM_VIGEM, 0x96E42B22, 0xF5E9, 0x42F8, 0xB0, 0x43, 0xED, 0x0F, 0x93, 0x2F, 0x01, 0x4F); #pragma once #include "ViGEmCommon.h" // // Common version for user-mode library and driver compatibility // // On initialization, the user-mode library has this number embedded // and sends it to the bus on its enumeration. The bus compares this // number to the one it was compiled with. If they match, the bus // access is permitted and success reported. If they mismatch, an // error is reported and the user-mode library skips this instance. // #define VIGEM_COMMON_VERSION 0x0001 #define FILE_DEVICE_BUSENUM FILE_DEVICE_BUS_EXTENDER #define BUSENUM_IOCTL(_index_) CTL_CODE(FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_READ_DATA) #define BUSENUM_W_IOCTL(_index_) CTL_CODE(FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_WRITE_DATA) #define BUSENUM_R_IOCTL(_index_) CTL_CODE(FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_READ_DATA) #define BUSENUM_RW_IOCTL(_index_) CTL_CODE(FILE_DEVICE_BUSENUM, _index_, METHOD_BUFFERED, FILE_WRITE_DATA | FILE_READ_DATA) #define IOCTL_VIGEM_BASE 0x801 // // IO control codes // #define IOCTL_VIGEM_PLUGIN_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x000) #define IOCTL_VIGEM_UNPLUG_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x001) #define IOCTL_VIGEM_CHECK_VERSION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x002) #define IOCTL_XUSB_REQUEST_NOTIFICATION BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x200) #define IOCTL_XUSB_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x201) #define IOCTL_DS4_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x202) #define IOCTL_DS4_REQUEST_NOTIFICATION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x203) #define IOCTL_XGIP_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x204) #define IOCTL_XGIP_SUBMIT_INTERRUPT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x205) // // Data structure used in PlugIn and UnPlug ioctls // #pragma region Plugin // // Data structure used in IOCTL_VIGEM_PLUGIN_TARGET requests. // typedef struct _VIGEM_PLUGIN_TARGET { // // sizeof (struct _BUSENUM_HARDWARE) // IN ULONG Size; // // Serial number of target device. // IN ULONG SerialNo; // // Type of the target device to emulate. // VIGEM_TARGET_TYPE TargetType; // // If set, the vendor ID the emulated device is reporting // USHORT VendorId; // // If set, the product ID the emulated device is reporting // USHORT ProductId; } VIGEM_PLUGIN_TARGET, *PVIGEM_PLUGIN_TARGET; // // Initializes a VIGEM_PLUGIN_TARGET structure. // VOID FORCEINLINE VIGEM_PLUGIN_TARGET_INIT( _Out_ PVIGEM_PLUGIN_TARGET PlugIn, _In_ ULONG SerialNo, _In_ VIGEM_TARGET_TYPE TargetType ) { RtlZeroMemory(PlugIn, sizeof(VIGEM_PLUGIN_TARGET)); PlugIn->Size = sizeof(VIGEM_PLUGIN_TARGET); PlugIn->SerialNo = SerialNo; PlugIn->TargetType = TargetType; } #pragma endregion #pragma region Unplug // // Data structure used in IOCTL_VIGEM_UNPLUG_TARGET requests. // typedef struct _VIGEM_UNPLUG_TARGET { // // sizeof (struct _REMOVE_HARDWARE) // IN ULONG Size; // // Serial number of target device. // ULONG SerialNo; } VIGEM_UNPLUG_TARGET, *PVIGEM_UNPLUG_TARGET; // // Initializes a VIGEM_UNPLUG_TARGET structure. // VOID FORCEINLINE VIGEM_UNPLUG_TARGET_INIT( _Out_ PVIGEM_UNPLUG_TARGET UnPlug, _In_ ULONG SerialNo ) { RtlZeroMemory(UnPlug, sizeof(VIGEM_UNPLUG_TARGET)); UnPlug->Size = sizeof(VIGEM_UNPLUG_TARGET); UnPlug->SerialNo = SerialNo; } #pragma endregion #pragma region Check version typedef struct _VIGEM_CHECK_VERSION { IN ULONG Size; IN ULONG Version; } VIGEM_CHECK_VERSION, *PVIGEM_CHECK_VERSION; VOID FORCEINLINE VIGEM_CHECK_VERSION_INIT( _Out_ PVIGEM_CHECK_VERSION CheckVersion, _In_ ULONG Version ) { RtlZeroMemory(CheckVersion, sizeof(VIGEM_CHECK_VERSION)); CheckVersion->Size = sizeof(VIGEM_CHECK_VERSION); CheckVersion->Version = Version; } #pragma endregion #pragma region XUSB (aka Xbox 360 device) section // // Data structure used in IOCTL_XUSB_REQUEST_NOTIFICATION requests. // typedef struct _XUSB_REQUEST_NOTIFICATION { // // sizeof(struct _XUSB_REQUEST_NOTIFICATION) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // Vibration intensity value of the large motor (0-255). // UCHAR LargeMotor; // // Vibration intensity value of the small motor (0-255). // UCHAR SmallMotor; // // Index number of the slot/LED that XUSB.sys has assigned. // UCHAR LedNumber; } XUSB_REQUEST_NOTIFICATION, *PXUSB_REQUEST_NOTIFICATION; // // Initializes a XUSB_REQUEST_NOTIFICATION structure. // VOID FORCEINLINE XUSB_REQUEST_NOTIFICATION_INIT( _Out_ PXUSB_REQUEST_NOTIFICATION Request, _In_ ULONG SerialNo ) { RtlZeroMemory(Request, sizeof(XUSB_REQUEST_NOTIFICATION)); Request->Size = sizeof(XUSB_REQUEST_NOTIFICATION); Request->SerialNo = SerialNo; } // // Data structure used in IOCTL_XUSB_SUBMIT_REPORT requests. // typedef struct _XUSB_SUBMIT_REPORT { // // sizeof(struct _XUSB_SUBMIT_REPORT) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // Report to submit to the target device. // XUSB_REPORT Report; } XUSB_SUBMIT_REPORT, *PXUSB_SUBMIT_REPORT; // // Initializes an XUSB report. // VOID FORCEINLINE XUSB_SUBMIT_REPORT_INIT( _Out_ PXUSB_SUBMIT_REPORT Report, _In_ ULONG SerialNo ) { RtlZeroMemory(Report, sizeof(XUSB_SUBMIT_REPORT)); Report->Size = sizeof(XUSB_SUBMIT_REPORT); Report->SerialNo = SerialNo; } #pragma endregion #pragma region DualShock 4 section typedef struct _DS4_OUTPUT_REPORT { // // Vibration intensity value of the small motor (0-255). // UCHAR SmallMotor; // // Vibration intensity value of the large motor (0-255). // UCHAR LargeMotor; // // Color values of the Lightbar. // DS4_LIGHTBAR_COLOR LightbarColor; } DS4_OUTPUT_REPORT, *PDS4_OUTPUT_REPORT; // // Data structure used in IOCTL_DS4_REQUEST_NOTIFICATION requests. // typedef struct _DS4_REQUEST_NOTIFICATION { // // sizeof(struct _XUSB_REQUEST_NOTIFICATION) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // The HID output report // DS4_OUTPUT_REPORT Report; } DS4_REQUEST_NOTIFICATION, *PDS4_REQUEST_NOTIFICATION; // // Initializes a DS4_REQUEST_NOTIFICATION structure. // VOID FORCEINLINE DS4_REQUEST_NOTIFICATION_INIT( _Out_ PDS4_REQUEST_NOTIFICATION Request, _In_ ULONG SerialNo ) { RtlZeroMemory(Request, sizeof(DS4_REQUEST_NOTIFICATION)); Request->Size = sizeof(DS4_REQUEST_NOTIFICATION); Request->SerialNo = SerialNo; } // // DualShock 4 request data // typedef struct _DS4_SUBMIT_REPORT { // // sizeof(struct _DS4_SUBMIT_REPORT) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // HID Input report // DS4_REPORT Report; } DS4_SUBMIT_REPORT, *PDS4_SUBMIT_REPORT; // // Initializes a DualShock 4 report. // VOID FORCEINLINE DS4_SUBMIT_REPORT_INIT( _Out_ PDS4_SUBMIT_REPORT Report, _In_ ULONG SerialNo ) { RtlZeroMemory(Report, sizeof(DS4_SUBMIT_REPORT)); Report->Size = sizeof(DS4_SUBMIT_REPORT); Report->SerialNo = SerialNo; DS4_REPORT_INIT(&Report->Report); } #pragma endregion #pragma region XGIP (aka Xbox One device) section - EXPERIMENTAL typedef struct _XGIP_REPORT { UCHAR Buttons1; UCHAR Buttons2; SHORT LeftTrigger; SHORT RightTrigger; SHORT ThumbLX; SHORT ThumbLY; SHORT ThumbRX; SHORT ThumbRY; } XGIP_REPORT, *PXGIP_REPORT; // // Xbox One request data // typedef struct _XGIP_SUBMIT_REPORT { // // sizeof(struct _XGIP_SUBMIT_REPORT) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // HID Input report // XGIP_REPORT Report; } XGIP_SUBMIT_REPORT, *PXGIP_SUBMIT_REPORT; // // Initializes an Xbox One report. // VOID FORCEINLINE XGIP_SUBMIT_REPORT_INIT( _Out_ PXGIP_SUBMIT_REPORT Report, _In_ ULONG SerialNo ) { RtlZeroMemory(Report, sizeof(XGIP_SUBMIT_REPORT)); Report->Size = sizeof(XGIP_SUBMIT_REPORT); Report->SerialNo = SerialNo; } // // Xbox One interrupt data // typedef struct _XGIP_SUBMIT_INTERRUPT { // // sizeof(struct _XGIP_SUBMIT_INTERRUPT) // ULONG Size; // // Serial number of target device. // ULONG SerialNo; // // Interrupt buffer. // UCHAR Interrupt[64]; // // Length of interrupt buffer. // ULONG InterruptLength; } XGIP_SUBMIT_INTERRUPT, *PXGIP_SUBMIT_INTERRUPT; // // Initializes an Xbox One interrupt. // VOID FORCEINLINE XGIP_SUBMIT_INTERRUPT_INIT( _Out_ PXGIP_SUBMIT_INTERRUPT Report, _In_ ULONG SerialNo ) { RtlZeroMemory(Report, sizeof(XGIP_SUBMIT_INTERRUPT)); Report->Size = sizeof(XGIP_SUBMIT_INTERRUPT); Report->SerialNo = SerialNo; } #pragma endregion ================================================ FILE: ThirdParty/ViGEm/Include/ViGEmClient.h ================================================ /* MIT License Copyright (c) 2017 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef ViGEmClient_h__ #define ViGEmClient_h__ #ifdef __cplusplus extern "C" { #endif #include "ViGEmCommon.h" #ifdef VIGEM_DYNAMIC #ifdef VIGEM_EXPORTS #define VIGEM_API __declspec(dllexport) #else #define VIGEM_API __declspec(dllimport) #endif #else #define VIGEM_API #endif /** * \typedef enum _VIGEM_ERRORS * * \brief Defines an alias representing the ViGEm errors. */ typedef enum _VIGEM_ERRORS { VIGEM_ERROR_NONE = 0x20000000, VIGEM_ERROR_BUS_NOT_FOUND = 0xE0000001, VIGEM_ERROR_NO_FREE_SLOT = 0xE0000002, VIGEM_ERROR_INVALID_TARGET = 0xE0000003, VIGEM_ERROR_REMOVAL_FAILED = 0xE0000004, VIGEM_ERROR_ALREADY_CONNECTED = 0xE0000005, VIGEM_ERROR_TARGET_UNINITIALIZED = 0xE0000006, VIGEM_ERROR_TARGET_NOT_PLUGGED_IN = 0xE0000007, VIGEM_ERROR_BUS_VERSION_MISMATCH = 0xE0000008, VIGEM_ERROR_BUS_ACCESS_FAILED = 0xE0000009, VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED = 0xE0000010, VIGEM_ERROR_CALLBACK_NOT_FOUND = 0xE0000011, VIGEM_ERROR_BUS_ALREADY_CONNECTED = 0xE0000012 } VIGEM_ERROR; /** * \def VIGEM_SUCCESS(_val_) (_val_ == VIGEM_ERROR_NONE); * * \brief A macro that defines success. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param _val_ The VIGEM_ERROR value. */ #define VIGEM_SUCCESS(_val_) (_val_ == VIGEM_ERROR_NONE) /** * \typedef struct _VIGEM_CLIENT_T *PVIGEM_CLIENT * * \brief Defines an alias representing a driver connection object. */ typedef struct _VIGEM_CLIENT_T *PVIGEM_CLIENT; /** * \typedef struct _VIGEM_TARGET_T *PVIGEM_TARGET * * \brief Defines an alias representing a target device object. */ typedef struct _VIGEM_TARGET_T *PVIGEM_TARGET; typedef VOID(CALLBACK* PVIGEM_X360_NOTIFICATION)( PVIGEM_CLIENT Client, PVIGEM_TARGET Target, UCHAR LargeMotor, UCHAR SmallMotor, UCHAR LedNumber); typedef VOID(CALLBACK* PVIGEM_DS4_NOTIFICATION)( PVIGEM_CLIENT Client, PVIGEM_TARGET Target, UCHAR LargeMotor, UCHAR SmallMotor, DS4_LIGHTBAR_COLOR LightbarColor); typedef VOID(CALLBACK* PVIGEM_TARGET_ADD_RESULT)( PVIGEM_CLIENT Client, PVIGEM_TARGET Target, VIGEM_ERROR Result); /** * \fn PVIGEM_CLIENT vigem_alloc(void); * * \brief Allocates an object representing a driver connection. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \return A new driver connection object. */ VIGEM_API PVIGEM_CLIENT vigem_alloc(void); /** * \fn void vigem_free(PVIGEM_CLIENT vigem); * * \brief Frees up memory used by the driver connection object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. */ VIGEM_API void vigem_free(PVIGEM_CLIENT vigem); /** * \fn VIGEM_ERROR vigem_connect(PVIGEM_CLIENT vigem); * * \brief Initializes the driver object and establishes a connection to the emulation bus * driver. Returns an error if no compatible bus device has been found. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_connect(PVIGEM_CLIENT vigem); /** * \fn void vigem_disconnect(PVIGEM_CLIENT vigem); * * \brief Disconnects from the bus device and resets the driver object state. The driver object * may be reused again after calling this function. When called, all targets which may * still be connected will be destroyed automatically. Be aware, that allocated target * objects won't be automatically freed, this has to be taken care of by the caller. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. */ VIGEM_API void vigem_disconnect(PVIGEM_CLIENT vigem); /** * \fn PVIGEM_TARGET vigem_target_x360_alloc(void); * * \brief Allocates an object representing an Xbox 360 Controller device. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \return A PVIGEM_TARGET representing an Xbox 360 Controller device. */ VIGEM_API PVIGEM_TARGET vigem_target_x360_alloc(void); /** * \fn PVIGEM_TARGET vigem_target_ds4_alloc(void); * * \brief Allocates an object representing a DualShock 4 Controller device. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \return A PVIGEM_TARGET representing a DualShock 4 Controller device. */ VIGEM_API PVIGEM_TARGET vigem_target_ds4_alloc(void); /** * \fn void vigem_target_free(PVIGEM_TARGET target); * * \brief Frees up memory used by the target device object. This does not automatically remove * the associated device from the bus, if present. If the target device doesn't get * removed before this call, the device becomes orphaned until the owning process is * terminated. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. */ VIGEM_API void vigem_target_free(PVIGEM_TARGET target); /** * \fn VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); * * \brief Adds a provided target device to the bus driver, which is equal to a device plug-in * event of a physical hardware device. This function blocks until the target device is * in full operational mode. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); /** * \fn VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_TARGET_ADD_RESULT result); * * \brief Adds a provided target device to the bus driver, which is equal to a device plug-in * event of a physical hardware device. This function immediately returns. An optional * callback may be registered which gets called on error or if the target device has * become fully operational. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * \param result An optional function getting called when the target device becomes available. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_TARGET_ADD_RESULT result); /** * \fn VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); * * \brief Removes a provided target device from the bus driver, which is equal to a device * unplug event of a physical hardware device. The target device object may be reused * after this function is called. If this function is never called on target device * objects, they will be removed from the bus when the owning process terminates. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); /** * \fn VIGEM_ERROR vigem_target_x360_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_X360_NOTIFICATION notification); * * \brief Registers a function which gets called, when LED index or vibration state changes * occur on the provided target device. This function fails if the provided target * device isn't fully operational or in an erroneous state. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * \param notification The notification callback. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_x360_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_X360_NOTIFICATION notification); /** * \fn VIGEM_ERROR vigem_target_ds4_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_DS4_NOTIFICATION notification); * * \brief Registers a function which gets called, when LightBar or vibration state changes * occur on the provided target device. This function fails if the provided target * device isn't fully operational or in an erroneous state. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * \param notification The notification callback. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_ds4_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_DS4_NOTIFICATION notification); /** * \fn void vigem_target_x360_unregister_notification(PVIGEM_TARGET target); * * \brief Removes a previously registered callback function from the provided target object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. */ VIGEM_API void vigem_target_x360_unregister_notification(PVIGEM_TARGET target); /** * \fn void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target); * * \brief Removes a previously registered callback function from the provided target object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. */ VIGEM_API void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target); /** * \fn void vigem_target_set_vid(PVIGEM_TARGET target, USHORT vid); * * \brief Overrides the default Vendor ID value with the provided one. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * \param vid The Vendor ID to set. */ VIGEM_API void vigem_target_set_vid(PVIGEM_TARGET target, USHORT vid); /** * \fn void vigem_target_set_pid(PVIGEM_TARGET target, USHORT pid); * * \brief Overrides the default Product ID value with the provided one. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * \param pid The Product ID to set. */ VIGEM_API void vigem_target_set_pid(PVIGEM_TARGET target, USHORT pid); /** * \fn USHORT vigem_target_get_vid(PVIGEM_TARGET target); * * \brief Returns the Vendor ID of the provided target device object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * * \return The Vendor ID. */ VIGEM_API USHORT vigem_target_get_vid(PVIGEM_TARGET target); /** * \fn USHORT vigem_target_get_pid(PVIGEM_TARGET target); * * \brief Returns the Product ID of the provided target device object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * * \return The Product ID. */ VIGEM_API USHORT vigem_target_get_pid(PVIGEM_TARGET target); /** * \fn VIGEM_ERROR vigem_target_x360_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, XUSB_REPORT report); * * \brief Sends a state report to the provided target device. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * \param report The report to send to the target device. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_x360_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, XUSB_REPORT report); /** * \fn VIGEM_ERROR vigem_target_ds4_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, DS4_REPORT report); * * \brief Sends a state report to the provided target device. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param vigem The driver connection object. * \param target The target device object. * \param report The report to send to the target device. * * \return A VIGEM_ERROR. */ VIGEM_API VIGEM_ERROR vigem_target_ds4_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, DS4_REPORT report); /** * \fn ULONG vigem_target_get_index(PVIGEM_TARGET target); * * \brief Returns the internal index (serial number) the bus driver assigned to the provided * target device object. Note that this value is specific to the inner workings of the * bus driver, it does not reflect related values like player index or device arrival * order experienced by other APIs. It may be used to identify the target device object * for its lifetime. This value becomes invalid once the target device is removed from * the bus and may change on the next addition of the device. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * * \return The internally used index of the target device. */ VIGEM_API ULONG vigem_target_get_index(PVIGEM_TARGET target); /** * \fn VIGEM_TARGET_TYPE vigem_target_get_type(PVIGEM_TARGET target); * * \brief Returns the type of the provided target device object. * * \author Benjamin "Nefarius" Hglinger * \date 28.08.2017 * * \param target The target device object. * * \return A VIGEM_TARGET_TYPE. */ VIGEM_API VIGEM_TARGET_TYPE vigem_target_get_type(PVIGEM_TARGET target); /** * \fn BOOL vigem_target_is_attached(PVIGEM_TARGET target); * * \brief Returns TRUE if the provided target device object is currently attached to the bus, * FALSE otherwise. * * \author Benjamin "Nefarius" Hglinger * \date 30.08.2017 * * \param target The target device object. * * \return TRUE if device is attached to the bus, FALSE otherwise. */ VIGEM_API BOOL vigem_target_is_attached(PVIGEM_TARGET target); #ifdef __cplusplus } #endif #endif // ViGEmClient_h__ ================================================ FILE: ThirdParty/ViGEm/Include/ViGEmCommon.h ================================================ /* MIT License Copyright (c) 2017 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once // // Represents the desired target type for the emulated device. // typedef enum _VIGEM_TARGET_TYPE { // // Microsoft Xbox 360 Controller (wired) // Xbox360Wired, // // Microsoft Xbox One Controller (wired) // XboxOneWired, // // Sony DualShock 4 (wired) // DualShock4Wired } VIGEM_TARGET_TYPE, *PVIGEM_TARGET_TYPE; // // Possible XUSB report buttons. // typedef enum _XUSB_BUTTON { XUSB_GAMEPAD_DPAD_UP = 0x0001, XUSB_GAMEPAD_DPAD_DOWN = 0x0002, XUSB_GAMEPAD_DPAD_LEFT = 0x0004, XUSB_GAMEPAD_DPAD_RIGHT = 0x0008, XUSB_GAMEPAD_START = 0x0010, XUSB_GAMEPAD_BACK = 0x0020, XUSB_GAMEPAD_LEFT_THUMB = 0x0040, XUSB_GAMEPAD_RIGHT_THUMB = 0x0080, XUSB_GAMEPAD_LEFT_SHOULDER = 0x0100, XUSB_GAMEPAD_RIGHT_SHOULDER = 0x0200, XUSB_GAMEPAD_GUIDE = 0x0400, XUSB_GAMEPAD_A = 0x1000, XUSB_GAMEPAD_B = 0x2000, XUSB_GAMEPAD_X = 0x4000, XUSB_GAMEPAD_Y = 0x8000 } XUSB_BUTTON, *PXUSB_BUTTON; // // Represents an XINPUT_GAMEPAD-compatible report structure. // typedef struct _XUSB_REPORT { USHORT wButtons; BYTE bLeftTrigger; BYTE bRightTrigger; SHORT sThumbLX; SHORT sThumbLY; SHORT sThumbRX; SHORT sThumbRY; } XUSB_REPORT, *PXUSB_REPORT; // // Initializes a _XUSB_REPORT structure. // VOID FORCEINLINE XUSB_REPORT_INIT( _Out_ PXUSB_REPORT Report ) { RtlZeroMemory(Report, sizeof(XUSB_REPORT)); } // // The color value (RGB) of a DualShock 4 Lightbar // typedef struct _DS4_LIGHTBAR_COLOR { // // Red part of the Lightbar (0-255). // UCHAR Red; // // Green part of the Lightbar (0-255). // UCHAR Green; // // Blue part of the Lightbar (0-255). // UCHAR Blue; } DS4_LIGHTBAR_COLOR, *PDS4_LIGHTBAR_COLOR; // // DualShock 4 digital buttons // typedef enum _DS4_BUTTONS { DS4_BUTTON_THUMB_RIGHT = 1 << 15, DS4_BUTTON_THUMB_LEFT = 1 << 14, DS4_BUTTON_OPTIONS = 1 << 13, DS4_BUTTON_SHARE = 1 << 12, DS4_BUTTON_TRIGGER_RIGHT = 1 << 11, DS4_BUTTON_TRIGGER_LEFT = 1 << 10, DS4_BUTTON_SHOULDER_RIGHT = 1 << 9, DS4_BUTTON_SHOULDER_LEFT = 1 << 8, DS4_BUTTON_TRIANGLE = 1 << 7, DS4_BUTTON_CIRCLE = 1 << 6, DS4_BUTTON_CROSS = 1 << 5, DS4_BUTTON_SQUARE = 1 << 4 } DS4_BUTTONS, *PDS4_BUTTONS; // // DualShock 4 special buttons // typedef enum _DS4_SPECIAL_BUTTONS { DS4_SPECIAL_BUTTON_PS = 1 << 0, DS4_SPECIAL_BUTTON_TOUCHPAD = 1 << 1 } DS4_SPECIAL_BUTTONS, *PDS4_SPECIAL_BUTTONS; // // DualShock 4 directional pad (HAT) values // typedef enum _DS4_DPAD_DIRECTIONS { DS4_BUTTON_DPAD_NONE = 0x8, DS4_BUTTON_DPAD_NORTHWEST = 0x7, DS4_BUTTON_DPAD_WEST = 0x6, DS4_BUTTON_DPAD_SOUTHWEST = 0x5, DS4_BUTTON_DPAD_SOUTH = 0x4, DS4_BUTTON_DPAD_SOUTHEAST = 0x3, DS4_BUTTON_DPAD_EAST = 0x2, DS4_BUTTON_DPAD_NORTHEAST = 0x1, DS4_BUTTON_DPAD_NORTH = 0x0 } DS4_DPAD_DIRECTIONS, *PDS4_DPAD_DIRECTIONS; // // DualShock 4 HID Input report // typedef struct _DS4_REPORT { BYTE bThumbLX; BYTE bThumbLY; BYTE bThumbRX; BYTE bThumbRY; USHORT wButtons; BYTE bSpecial; BYTE bTriggerL; BYTE bTriggerR; } DS4_REPORT, *PDS4_REPORT; // // Sets the current state of the D-PAD on a DualShock 4 report. // VOID FORCEINLINE DS4_SET_DPAD( _Out_ PDS4_REPORT Report, _In_ DS4_DPAD_DIRECTIONS Dpad ) { Report->wButtons &= ~0xF; Report->wButtons |= (USHORT)Dpad; } VOID FORCEINLINE DS4_REPORT_INIT( _Out_ PDS4_REPORT Report ) { RtlZeroMemory(Report, sizeof(DS4_REPORT)); Report->bThumbLX = 0x80; Report->bThumbLY = 0x80; Report->bThumbRX = 0x80; Report->bThumbRY = 0x80; DS4_SET_DPAD(Report, DS4_BUTTON_DPAD_NONE); } ================================================ FILE: ThirdParty/ViGEm/Include/ViGEmUtil.h ================================================ #pragma once #include "ViGEmCommon.h" #include VOID FORCEINLINE XUSB_TO_DS4_REPORT( _Out_ PXUSB_REPORT Input, _Out_ PDS4_REPORT Output ) { if (Input->wButtons & XUSB_GAMEPAD_BACK) Output->wButtons |= DS4_BUTTON_SHARE; if (Input->wButtons & XUSB_GAMEPAD_START) Output->wButtons |= DS4_BUTTON_OPTIONS; if (Input->wButtons & XUSB_GAMEPAD_LEFT_THUMB) Output->wButtons |= DS4_BUTTON_THUMB_LEFT; if (Input->wButtons & XUSB_GAMEPAD_RIGHT_THUMB) Output->wButtons |= DS4_BUTTON_THUMB_RIGHT; if (Input->wButtons & XUSB_GAMEPAD_LEFT_SHOULDER) Output->wButtons |= DS4_BUTTON_SHOULDER_LEFT; if (Input->wButtons & XUSB_GAMEPAD_RIGHT_SHOULDER) Output->wButtons |= DS4_BUTTON_SHOULDER_RIGHT; if (Input->wButtons & XUSB_GAMEPAD_GUIDE) Output->bSpecial |= DS4_SPECIAL_BUTTON_PS; if (Input->wButtons & XUSB_GAMEPAD_A) Output->wButtons |= DS4_BUTTON_CROSS; if (Input->wButtons & XUSB_GAMEPAD_B) Output->wButtons |= DS4_BUTTON_CIRCLE; if (Input->wButtons & XUSB_GAMEPAD_X) Output->wButtons |= DS4_BUTTON_SQUARE; if (Input->wButtons & XUSB_GAMEPAD_Y) Output->wButtons |= DS4_BUTTON_TRIANGLE; Output->bTriggerL = Input->bLeftTrigger; Output->bTriggerR = Input->bRightTrigger; if (Input->bLeftTrigger > 0)Output->wButtons |= DS4_BUTTON_TRIGGER_LEFT; if (Input->bRightTrigger > 0)Output->wButtons |= DS4_BUTTON_TRIGGER_RIGHT; if (Input->wButtons & XUSB_GAMEPAD_DPAD_UP) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_NORTH); if (Input->wButtons & XUSB_GAMEPAD_DPAD_RIGHT) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_EAST); if (Input->wButtons & XUSB_GAMEPAD_DPAD_DOWN) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_SOUTH); if (Input->wButtons & XUSB_GAMEPAD_DPAD_LEFT) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_WEST); if (Input->wButtons & XUSB_GAMEPAD_DPAD_UP && Input->wButtons & XUSB_GAMEPAD_DPAD_RIGHT) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_NORTHEAST); if (Input->wButtons & XUSB_GAMEPAD_DPAD_RIGHT && Input->wButtons & XUSB_GAMEPAD_DPAD_DOWN) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_SOUTHEAST); if (Input->wButtons & XUSB_GAMEPAD_DPAD_DOWN && Input->wButtons & XUSB_GAMEPAD_DPAD_LEFT) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_SOUTHWEST); if (Input->wButtons & XUSB_GAMEPAD_DPAD_LEFT && Input->wButtons & XUSB_GAMEPAD_DPAD_UP) DS4_SET_DPAD(Output, DS4_BUTTON_DPAD_NORTHWEST); Output->bThumbLX = ((Input->sThumbLX + ((USHRT_MAX / 2) + 1)) / 257); Output->bThumbLY = (-(Input->sThumbLY + ((USHRT_MAX / 2) - 1)) / 257); Output->bThumbLY = (Output->bThumbLY == 0) ? 0xFF : Output->bThumbLY; Output->bThumbRX = ((Input->sThumbRX + ((USHRT_MAX / 2) + 1)) / 257); Output->bThumbRY = (-(Input->sThumbRY + ((USHRT_MAX / 2) + 1)) / 257); Output->bThumbRY = (Output->bThumbRY == 0) ? 0xFF : Output->bThumbRY; } ================================================ FILE: ThirdParty/ViGEm/Include/XInputOverrides.h ================================================ /* MIT License Copyright (c) 2016 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once typedef enum _XINPUT_GAMEPAD_OVERRIDES { XINPUT_GAMEPAD_OVERRIDE_DPAD_UP = 0x00000001, XINPUT_GAMEPAD_OVERRIDE_DPAD_DOWN = 0x00000002, XINPUT_GAMEPAD_OVERRIDE_DPAD_LEFT = 0x00000004, XINPUT_GAMEPAD_OVERRIDE_DPAD_RIGHT = 0x00000008, XINPUT_GAMEPAD_OVERRIDE_START = 0x00000010, XINPUT_GAMEPAD_OVERRIDE_BACK = 0x00000020, XINPUT_GAMEPAD_OVERRIDE_LEFT_THUMB = 0x00000040, XINPUT_GAMEPAD_OVERRIDE_RIGHT_THUMB = 0x00000080, XINPUT_GAMEPAD_OVERRIDE_LEFT_SHOULDER = 0x00000100, XINPUT_GAMEPAD_OVERRIDE_RIGHT_SHOULDER = 0x00000200, XINPUT_GAMEPAD_OVERRIDE_A = 0x00001000, XINPUT_GAMEPAD_OVERRIDE_B = 0x00002000, XINPUT_GAMEPAD_OVERRIDE_X = 0x00004000, XINPUT_GAMEPAD_OVERRIDE_Y = 0x00008000, XINPUT_GAMEPAD_OVERRIDE_LEFT_TRIGGER = 0x00010000, XINPUT_GAMEPAD_OVERRIDE_RIGHT_TRIGGER = 0x00020000, XINPUT_GAMEPAD_OVERRIDE_LEFT_THUMB_X = 0x00040000, XINPUT_GAMEPAD_OVERRIDE_LEFT_THUMB_Y = 0x00080000, XINPUT_GAMEPAD_OVERRIDE_RIGHT_THUMB_X = 0x00100000, XINPUT_GAMEPAD_OVERRIDE_RIGHT_THUMB_Y = 0x00200000 } XINPUT_GAMEPAD_OVERRIDES, *PXINPUT_GAMEPAD_OVERRIDES; ================================================ FILE: ThirdParty/ViGEm/Include/XnaGuardianShared.h ================================================ /* MIT License Copyright (c) 2016 Benjamin "Nefarius" Hglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #define XNA_GUARDIAN_DEVICE_PATH TEXT("\\\\.\\XnaGuardian") #define XINPUT_MAX_DEVICES 0x04 #define VALID_USER_INDEX(_index_) ((_index_ >= 0) && (_index_ < XINPUT_MAX_DEVICES)) // // Custom extensions // #define XINPUT_EXT_TYPE 0x8001 #define XINPUT_EXT_CODE 0x801 #define IOCTL_XINPUT_EXT_OVERRIDE_GAMEPAD_STATE CTL_CODE(XINPUT_EXT_TYPE, XINPUT_EXT_CODE + 0x01, METHOD_BUFFERED, FILE_WRITE_DATA) #define IOCTL_XINPUT_EXT_PEEK_GAMEPAD_STATE CTL_CODE(XINPUT_EXT_TYPE, XINPUT_EXT_CODE + 0x02, METHOD_BUFFERED, FILE_READ_DATA | FILE_WRITE_DATA) // // State of the gamepad (compatible to XINPUT_GAMEPAD) // typedef struct _XINPUT_GAMEPAD_STATE { USHORT wButtons; BYTE bLeftTrigger; BYTE bRightTrigger; SHORT sThumbLX; SHORT sThumbLY; SHORT sThumbRX; SHORT sThumbRY; } XINPUT_GAMEPAD_STATE, *PXINPUT_GAMEPAD_STATE; // // Context data for IOCTL_XINPUT_EXT_OVERRIDE_GAMEPAD_STATE I/O control code // typedef struct _XINPUT_EXT_OVERRIDE_GAMEPAD { IN ULONG Size; IN UCHAR UserIndex; IN ULONG Overrides; IN XINPUT_GAMEPAD_STATE Gamepad; } XINPUT_EXT_OVERRIDE_GAMEPAD, *PXINPUT_EXT_OVERRIDE_GAMEPAD; VOID FORCEINLINE XINPUT_EXT_OVERRIDE_GAMEPAD_INIT( _Out_ PXINPUT_EXT_OVERRIDE_GAMEPAD OverrideGamepad, _In_ UCHAR UserIndex ) { RtlZeroMemory(OverrideGamepad, sizeof(XINPUT_EXT_OVERRIDE_GAMEPAD)); OverrideGamepad->Size = sizeof(XINPUT_EXT_OVERRIDE_GAMEPAD); OverrideGamepad->UserIndex = UserIndex; } // // Context data for IOCTL_XINPUT_EXT_PEEK_GAMEPAD_STATE I/O control code // typedef struct _XINPUT_EXT_PEEK_GAMEPAD { IN ULONG Size; IN UCHAR UserIndex; } XINPUT_EXT_PEEK_GAMEPAD, *PXINPUT_EXT_PEEK_GAMEPAD; VOID FORCEINLINE XINPUT_EXT_PEEK_GAMEPAD_INIT( _Out_ PXINPUT_EXT_PEEK_GAMEPAD PeekGamepad, _In_ UCHAR UserIndex ) { RtlZeroMemory(PeekGamepad, sizeof(XINPUT_EXT_PEEK_GAMEPAD)); PeekGamepad->Size = sizeof(XINPUT_EXT_PEEK_GAMEPAD); PeekGamepad->UserIndex = UserIndex; } ================================================ FILE: ThirdParty/ViGEm/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Benjamin Höglinger Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: ThirdParty/ffmpeg/LICENSE.txt ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: ThirdParty/ffmpeg/README.txt ================================================ Zeranoe FFmpeg Builds Build: ffmpeg-4.0.2-win32-shared Configuration: --disable-static --enable-shared --enable-gpl --enable-version3 --enable-sdl2 --enable-bzlib --enable-fontconfig --enable-gnutls --enable-iconv --enable-libass --enable-libbluray --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libopus --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libtheora --enable-libtwolame --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libzimg --enable-lzma --enable-zlib --enable-gmp --enable-libvidstab --enable-libvorbis --enable-libvo-amrwbenc --enable-libmysofa --enable-libspeex --enable-libxvid --enable-libaom --enable-libmfx --enable-amf --enable-ffnvcodec --enable-cuvid --enable-d3d11va --enable-nvenc --enable-nvdec --enable-dxva2 --enable-avisynth Libraries: SDL 2.0.8 bzip2 1.0.6 Fontconfig 2.13.0 GnuTLS 3.5.19 libiconv 1.15 libass 0.14.0 libbluray 20180309-8c15fda FreeType 2.9.1 LAME 3.100 OpenCORE AMR 20170731-07a5be4 OpenJPEG 2.3.0 Opus 20180614-c1c247d shine 3.1.1 Snappy 1.1.7 libsoxr 20180224-945b592 Theora 1.1.1 TwoLAME 0.3.13 vpx 1.7.0 WavPack 5.1.0 WebP 1.0.0 x264 20180118-7d0ff22 x265 20180725-79c76e4 libxml2 2.9.8 z.lib 20180713-654c15b XZ Utils 5.2.4 zlib 1.2.11 GMP 6.1.2 vid.stab 20180529-38ecbaf Vorbis 1.3.5 VisualOn AMR-WB 20141107-3b3fcd0 libmysofa 20171120-cec6eea Speex 1.2.0 Xvid 1.3.5 aom 20180725-b0c13b2 libmfx 1.23 AMF 20171219-801247d nv-codec-headers 20180507-91d9e20 Copyright (C) 2018 Kyle Schwarz This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ================================================ FILE: ThirdParty/ffmpeg/examples/Makefile ================================================ # use pkg-config for getting CFLAGS and LDLIBS FFMPEG_LIBS= libavdevice \ libavformat \ libavfilter \ libavcodec \ libswresample \ libswscale \ libavutil \ CFLAGS += -Wall -g CFLAGS := $(shell pkg-config --cflags $(FFMPEG_LIBS)) $(CFLAGS) LDLIBS := $(shell pkg-config --libs $(FFMPEG_LIBS)) $(LDLIBS) EXAMPLES= avio_dir_cmd \ avio_reading \ decode_audio \ decode_video \ demuxing_decoding \ encode_audio \ encode_video \ extract_mvs \ filtering_video \ filtering_audio \ http_multiclient \ hw_decode \ metadata \ muxing \ remuxing \ resampling_audio \ scaling_video \ transcode_aac \ transcoding \ OBJS=$(addsuffix .o,$(EXAMPLES)) # the following examples make explicit use of the math library avcodec: LDLIBS += -lm encode_audio: LDLIBS += -lm muxing: LDLIBS += -lm resampling_audio: LDLIBS += -lm .phony: all clean-test clean all: $(OBJS) $(EXAMPLES) clean-test: $(RM) test*.pgm test.h264 test.mp2 test.sw test.mpg clean: clean-test $(RM) $(EXAMPLES) $(OBJS) ================================================ FILE: ThirdParty/ffmpeg/examples/README ================================================ FFmpeg examples README ---------------------- Both following use cases rely on pkg-config and make, thus make sure that you have them installed and working on your system. Method 1: build the installed examples in a generic read/write user directory Copy to a read/write user directory and just use "make", it will link to the libraries on your system, assuming the PKG_CONFIG_PATH is correctly configured. Method 2: build the examples in-tree Assuming you are in the source FFmpeg checkout directory, you need to build FFmpeg (no need to make install in any prefix). Then just run "make examples". This will build the examples using the FFmpeg build system. You can clean those examples using "make examplesclean" If you want to try the dedicated Makefile examples (to emulate the first method), go into doc/examples and run a command such as PKG_CONFIG_PATH=pc-uninstalled make. ================================================ FILE: ThirdParty/ffmpeg/examples/avio_dir_cmd.c ================================================ /* * Copyright (c) 2014 Lukasz Marek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include #include static const char *type_string(int type) { switch (type) { case AVIO_ENTRY_DIRECTORY: return ""; case AVIO_ENTRY_FILE: return ""; case AVIO_ENTRY_BLOCK_DEVICE: return ""; case AVIO_ENTRY_CHARACTER_DEVICE: return ""; case AVIO_ENTRY_NAMED_PIPE: return ""; case AVIO_ENTRY_SYMBOLIC_LINK: return ""; case AVIO_ENTRY_SOCKET: return ""; case AVIO_ENTRY_SERVER: return ""; case AVIO_ENTRY_SHARE: return ""; case AVIO_ENTRY_WORKGROUP: return ""; case AVIO_ENTRY_UNKNOWN: default: break; } return ""; } static int list_op(const char *input_dir) { AVIODirEntry *entry = NULL; AVIODirContext *ctx = NULL; int cnt, ret; char filemode[4], uid_and_gid[20]; if ((ret = avio_open_dir(&ctx, input_dir, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot open directory: %s.\n", av_err2str(ret)); goto fail; } cnt = 0; for (;;) { if ((ret = avio_read_dir(ctx, &entry)) < 0) { av_log(NULL, AV_LOG_ERROR, "Cannot list directory: %s.\n", av_err2str(ret)); goto fail; } if (!entry) break; if (entry->filemode == -1) { snprintf(filemode, 4, "???"); } else { snprintf(filemode, 4, "%3"PRIo64, entry->filemode); } snprintf(uid_and_gid, 20, "%"PRId64"(%"PRId64")", entry->user_id, entry->group_id); if (cnt == 0) av_log(NULL, AV_LOG_INFO, "%-9s %12s %30s %10s %s %16s %16s %16s\n", "TYPE", "SIZE", "NAME", "UID(GID)", "UGO", "MODIFIED", "ACCESSED", "STATUS_CHANGED"); av_log(NULL, AV_LOG_INFO, "%-9s %12"PRId64" %30s %10s %s %16"PRId64" %16"PRId64" %16"PRId64"\n", type_string(entry->type), entry->size, entry->name, uid_and_gid, filemode, entry->modification_timestamp, entry->access_timestamp, entry->status_change_timestamp); avio_free_directory_entry(&entry); cnt++; }; fail: avio_close_dir(&ctx); return ret; } static int del_op(const char *url) { int ret = avpriv_io_delete(url); if (ret < 0) av_log(NULL, AV_LOG_ERROR, "Cannot delete '%s': %s.\n", url, av_err2str(ret)); return ret; } static int move_op(const char *src, const char *dst) { int ret = avpriv_io_move(src, dst); if (ret < 0) av_log(NULL, AV_LOG_ERROR, "Cannot move '%s' into '%s': %s.\n", src, dst, av_err2str(ret)); return ret; } static void usage(const char *program_name) { fprintf(stderr, "usage: %s OPERATION entry1 [entry2]\n" "API example program to show how to manipulate resources " "accessed through AVIOContext.\n" "OPERATIONS:\n" "list list content of the directory\n" "move rename content in directory\n" "del delete content in directory\n", program_name); } int main(int argc, char *argv[]) { const char *op = NULL; int ret; av_log_set_level(AV_LOG_DEBUG); if (argc < 2) { usage(argv[0]); return 1; } avformat_network_init(); op = argv[1]; if (strcmp(op, "list") == 0) { if (argc < 3) { av_log(NULL, AV_LOG_INFO, "Missing argument for list operation.\n"); ret = AVERROR(EINVAL); } else { ret = list_op(argv[2]); } } else if (strcmp(op, "del") == 0) { if (argc < 3) { av_log(NULL, AV_LOG_INFO, "Missing argument for del operation.\n"); ret = AVERROR(EINVAL); } else { ret = del_op(argv[2]); } } else if (strcmp(op, "move") == 0) { if (argc < 4) { av_log(NULL, AV_LOG_INFO, "Missing argument for move operation.\n"); ret = AVERROR(EINVAL); } else { ret = move_op(argv[2], argv[3]); } } else { av_log(NULL, AV_LOG_INFO, "Invalid operation %s\n", op); ret = AVERROR(EINVAL); } avformat_network_deinit(); return ret < 0 ? 1 : 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/avio_reading.c ================================================ /* * Copyright (c) 2014 Stefano Sabatini * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * libavformat AVIOContext API example. * * Make libavformat demuxer access media content through a custom * AVIOContext read callback. * @example avio_reading.c */ #include #include #include #include struct buffer_data { uint8_t *ptr; size_t size; ///< size left in the buffer }; static int read_packet(void *opaque, uint8_t *buf, int buf_size) { struct buffer_data *bd = (struct buffer_data *)opaque; buf_size = FFMIN(buf_size, bd->size); if (!buf_size) return AVERROR_EOF; printf("ptr:%p size:%zu\n", bd->ptr, bd->size); /* copy internal buffer data to buf */ memcpy(buf, bd->ptr, buf_size); bd->ptr += buf_size; bd->size -= buf_size; return buf_size; } int main(int argc, char *argv[]) { AVFormatContext *fmt_ctx = NULL; AVIOContext *avio_ctx = NULL; uint8_t *buffer = NULL, *avio_ctx_buffer = NULL; size_t buffer_size, avio_ctx_buffer_size = 4096; char *input_filename = NULL; int ret = 0; struct buffer_data bd = { 0 }; if (argc != 2) { fprintf(stderr, "usage: %s input_file\n" "API example program to show how to read from a custom buffer " "accessed through AVIOContext.\n", argv[0]); return 1; } input_filename = argv[1]; /* slurp file content into buffer */ ret = av_file_map(input_filename, &buffer, &buffer_size, 0, NULL); if (ret < 0) goto end; /* fill opaque structure used by the AVIOContext read callback */ bd.ptr = buffer; bd.size = buffer_size; if (!(fmt_ctx = avformat_alloc_context())) { ret = AVERROR(ENOMEM); goto end; } avio_ctx_buffer = av_malloc(avio_ctx_buffer_size); if (!avio_ctx_buffer) { ret = AVERROR(ENOMEM); goto end; } avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size, 0, &bd, &read_packet, NULL, NULL); if (!avio_ctx) { ret = AVERROR(ENOMEM); goto end; } fmt_ctx->pb = avio_ctx; ret = avformat_open_input(&fmt_ctx, NULL, NULL, NULL); if (ret < 0) { fprintf(stderr, "Could not open input\n"); goto end; } ret = avformat_find_stream_info(fmt_ctx, NULL); if (ret < 0) { fprintf(stderr, "Could not find stream information\n"); goto end; } av_dump_format(fmt_ctx, 0, input_filename, 0); end: avformat_close_input(&fmt_ctx); /* note: the internal buffer could have changed, and be != avio_ctx_buffer */ if (avio_ctx) { av_freep(&avio_ctx->buffer); av_freep(&avio_ctx); } av_file_unmap(buffer, buffer_size); if (ret < 0) { fprintf(stderr, "Error occurred: %s\n", av_err2str(ret)); return 1; } return 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/decode_audio.c ================================================ /* * Copyright (c) 2001 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * audio decoding with libavcodec API example * * @example decode_audio.c */ #include #include #include #include #include #include #define AUDIO_INBUF_SIZE 20480 #define AUDIO_REFILL_THRESH 4096 static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame, FILE *outfile) { int i, ch; int ret, data_size; /* send the packet with the compressed data to the decoder */ ret = avcodec_send_packet(dec_ctx, pkt); if (ret < 0) { fprintf(stderr, "Error submitting the packet to the decoder\n"); exit(1); } /* read all the output frames (in general there may be any number of them */ while (ret >= 0) { ret = avcodec_receive_frame(dec_ctx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) { fprintf(stderr, "Error during decoding\n"); exit(1); } data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt); if (data_size < 0) { /* This should not occur, checking just for paranoia */ fprintf(stderr, "Failed to calculate data size\n"); exit(1); } for (i = 0; i < frame->nb_samples; i++) for (ch = 0; ch < dec_ctx->channels; ch++) fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile); } } int main(int argc, char **argv) { const char *outfilename, *filename; const AVCodec *codec; AVCodecContext *c= NULL; AVCodecParserContext *parser = NULL; int len, ret; FILE *f, *outfile; uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; uint8_t *data; size_t data_size; AVPacket *pkt; AVFrame *decoded_frame = NULL; if (argc <= 2) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(0); } filename = argv[1]; outfilename = argv[2]; pkt = av_packet_alloc(); /* find the MPEG audio decoder */ codec = avcodec_find_decoder(AV_CODEC_ID_MP2); if (!codec) { fprintf(stderr, "Codec not found\n"); exit(1); } parser = av_parser_init(codec->id); if (!parser) { fprintf(stderr, "Parser not found\n"); exit(1); } c = avcodec_alloc_context3(codec); if (!c) { fprintf(stderr, "Could not allocate audio codec context\n"); exit(1); } /* open it */ if (avcodec_open2(c, codec, NULL) < 0) { fprintf(stderr, "Could not open codec\n"); exit(1); } f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Could not open %s\n", filename); exit(1); } outfile = fopen(outfilename, "wb"); if (!outfile) { av_free(c); exit(1); } /* decode until eof */ data = inbuf; data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f); while (data_size > 0) { if (!decoded_frame) { if (!(decoded_frame = av_frame_alloc())) { fprintf(stderr, "Could not allocate audio frame\n"); exit(1); } } ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (ret < 0) { fprintf(stderr, "Error while parsing\n"); exit(1); } data += ret; data_size -= ret; if (pkt->size) decode(c, pkt, decoded_frame, outfile); if (data_size < AUDIO_REFILL_THRESH) { memmove(inbuf, data, data_size); data = inbuf; len = fread(data + data_size, 1, AUDIO_INBUF_SIZE - data_size, f); if (len > 0) data_size += len; } } /* flush the decoder */ pkt->data = NULL; pkt->size = 0; decode(c, pkt, decoded_frame, outfile); fclose(outfile); fclose(f); avcodec_free_context(&c); av_parser_close(parser); av_frame_free(&decoded_frame); av_packet_free(&pkt); return 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/decode_video.c ================================================ /* * Copyright (c) 2001 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * video decoding with libavcodec API example * * @example decode_video.c */ #include #include #include #include #define INBUF_SIZE 4096 static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize, char *filename) { FILE *f; int i; f = fopen(filename,"w"); fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255); for (i = 0; i < ysize; i++) fwrite(buf + i * wrap, 1, xsize, f); fclose(f); } static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt, const char *filename) { char buf[1024]; int ret; ret = avcodec_send_packet(dec_ctx, pkt); if (ret < 0) { fprintf(stderr, "Error sending a packet for decoding\n"); exit(1); } while (ret >= 0) { ret = avcodec_receive_frame(dec_ctx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) { fprintf(stderr, "Error during decoding\n"); exit(1); } printf("saving frame %3d\n", dec_ctx->frame_number); fflush(stdout); /* the picture is allocated by the decoder. no need to free it */ snprintf(buf, sizeof(buf), "%s-%d", filename, dec_ctx->frame_number); pgm_save(frame->data[0], frame->linesize[0], frame->width, frame->height, buf); } } int main(int argc, char **argv) { const char *filename, *outfilename; const AVCodec *codec; AVCodecParserContext *parser; AVCodecContext *c= NULL; FILE *f; AVFrame *frame; uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE]; uint8_t *data; size_t data_size; int ret; AVPacket *pkt; if (argc <= 2) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(0); } filename = argv[1]; outfilename = argv[2]; pkt = av_packet_alloc(); if (!pkt) exit(1); /* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) */ memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE); /* find the MPEG-1 video decoder */ codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO); if (!codec) { fprintf(stderr, "Codec not found\n"); exit(1); } parser = av_parser_init(codec->id); if (!parser) { fprintf(stderr, "parser not found\n"); exit(1); } c = avcodec_alloc_context3(codec); if (!c) { fprintf(stderr, "Could not allocate video codec context\n"); exit(1); } /* For some codecs, such as msmpeg4 and mpeg4, width and height MUST be initialized there because this information is not available in the bitstream. */ /* open it */ if (avcodec_open2(c, codec, NULL) < 0) { fprintf(stderr, "Could not open codec\n"); exit(1); } f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Could not open %s\n", filename); exit(1); } frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate video frame\n"); exit(1); } while (!feof(f)) { /* read raw data from the input file */ data_size = fread(inbuf, 1, INBUF_SIZE, f); if (!data_size) break; /* use the parser to split the data into frames */ data = inbuf; while (data_size > 0) { ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size, data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (ret < 0) { fprintf(stderr, "Error while parsing\n"); exit(1); } data += ret; data_size -= ret; if (pkt->size) decode(c, frame, pkt, outfilename); } } /* flush the decoder */ decode(c, frame, NULL, outfilename); fclose(f); av_parser_close(parser); avcodec_free_context(&c); av_frame_free(&frame); av_packet_free(&pkt); return 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/demuxing_decoding.c ================================================ /* * Copyright (c) 2012 Stefano Sabatini * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * Demuxing and decoding example. * * Show how to use the libavformat and libavcodec API to demux and * decode audio and video data. * @example demuxing_decoding.c */ #include #include #include #include static AVFormatContext *fmt_ctx = NULL; static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx; static int width, height; static enum AVPixelFormat pix_fmt; static AVStream *video_stream = NULL, *audio_stream = NULL; static const char *src_filename = NULL; static const char *video_dst_filename = NULL; static const char *audio_dst_filename = NULL; static FILE *video_dst_file = NULL; static FILE *audio_dst_file = NULL; static uint8_t *video_dst_data[4] = {NULL}; static int video_dst_linesize[4]; static int video_dst_bufsize; static int video_stream_idx = -1, audio_stream_idx = -1; static AVFrame *frame = NULL; static AVPacket pkt; static int video_frame_count = 0; static int audio_frame_count = 0; /* Enable or disable frame reference counting. You are not supposed to support * both paths in your application but pick the one most appropriate to your * needs. Look for the use of refcount in this example to see what are the * differences of API usage between them. */ static int refcount = 0; static int decode_packet(int *got_frame, int cached) { int ret = 0; int decoded = pkt.size; *got_frame = 0; if (pkt.stream_index == video_stream_idx) { /* decode video frame */ ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt); if (ret < 0) { fprintf(stderr, "Error decoding video frame (%s)\n", av_err2str(ret)); return ret; } if (*got_frame) { if (frame->width != width || frame->height != height || frame->format != pix_fmt) { /* To handle this change, one could call av_image_alloc again and * decode the following frames into another rawvideo file. */ fprintf(stderr, "Error: Width, height and pixel format have to be " "constant in a rawvideo file, but the width, height or " "pixel format of the input video changed:\n" "old: width = %d, height = %d, format = %s\n" "new: width = %d, height = %d, format = %s\n", width, height, av_get_pix_fmt_name(pix_fmt), frame->width, frame->height, av_get_pix_fmt_name(frame->format)); return -1; } printf("video_frame%s n:%d coded_n:%d\n", cached ? "(cached)" : "", video_frame_count++, frame->coded_picture_number); /* copy decoded frame to destination buffer: * this is required since rawvideo expects non aligned data */ av_image_copy(video_dst_data, video_dst_linesize, (const uint8_t **)(frame->data), frame->linesize, pix_fmt, width, height); /* write to rawvideo file */ fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file); } } else if (pkt.stream_index == audio_stream_idx) { /* decode audio frame */ ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt); if (ret < 0) { fprintf(stderr, "Error decoding audio frame (%s)\n", av_err2str(ret)); return ret; } /* Some audio decoders decode only part of the packet, and have to be * called again with the remainder of the packet data. * Sample: fate-suite/lossless-audio/luckynight-partial.shn * Also, some decoders might over-read the packet. */ decoded = FFMIN(ret, pkt.size); if (*got_frame) { size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format); printf("audio_frame%s n:%d nb_samples:%d pts:%s\n", cached ? "(cached)" : "", audio_frame_count++, frame->nb_samples, av_ts2timestr(frame->pts, &audio_dec_ctx->time_base)); /* Write the raw audio data samples of the first plane. This works * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However, * most audio decoders output planar audio, which uses a separate * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P). * In other words, this code will write only the first audio channel * in these cases. * You should use libswresample or libavfilter to convert the frame * to packed data. */ fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file); } } /* If we use frame reference counting, we own the data and need * to de-reference it when we don't use it anymore */ if (*got_frame && refcount) av_frame_unref(frame); return decoded; } static int open_codec_context(int *stream_idx, AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type) { int ret, stream_index; AVStream *st; AVCodec *dec = NULL; AVDictionary *opts = NULL; ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0); if (ret < 0) { fprintf(stderr, "Could not find %s stream in input file '%s'\n", av_get_media_type_string(type), src_filename); return ret; } else { stream_index = ret; st = fmt_ctx->streams[stream_index]; /* find decoder for the stream */ dec = avcodec_find_decoder(st->codecpar->codec_id); if (!dec) { fprintf(stderr, "Failed to find %s codec\n", av_get_media_type_string(type)); return AVERROR(EINVAL); } /* Allocate a codec context for the decoder */ *dec_ctx = avcodec_alloc_context3(dec); if (!*dec_ctx) { fprintf(stderr, "Failed to allocate the %s codec context\n", av_get_media_type_string(type)); return AVERROR(ENOMEM); } /* Copy codec parameters from input stream to output codec context */ if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) { fprintf(stderr, "Failed to copy %s codec parameters to decoder context\n", av_get_media_type_string(type)); return ret; } /* Init the decoders, with or without reference counting */ av_dict_set(&opts, "refcounted_frames", refcount ? "1" : "0", 0); if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) { fprintf(stderr, "Failed to open %s codec\n", av_get_media_type_string(type)); return ret; } *stream_idx = stream_index; } return 0; } static int get_format_from_sample_fmt(const char **fmt, enum AVSampleFormat sample_fmt) { int i; struct sample_fmt_entry { enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le; } sample_fmt_entries[] = { { AV_SAMPLE_FMT_U8, "u8", "u8" }, { AV_SAMPLE_FMT_S16, "s16be", "s16le" }, { AV_SAMPLE_FMT_S32, "s32be", "s32le" }, { AV_SAMPLE_FMT_FLT, "f32be", "f32le" }, { AV_SAMPLE_FMT_DBL, "f64be", "f64le" }, }; *fmt = NULL; for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) { struct sample_fmt_entry *entry = &sample_fmt_entries[i]; if (sample_fmt == entry->sample_fmt) { *fmt = AV_NE(entry->fmt_be, entry->fmt_le); return 0; } } fprintf(stderr, "sample format %s is not supported as output format\n", av_get_sample_fmt_name(sample_fmt)); return -1; } int main (int argc, char **argv) { int ret = 0, got_frame; if (argc != 4 && argc != 5) { fprintf(stderr, "usage: %s [-refcount] input_file video_output_file audio_output_file\n" "API example program to show how to read frames from an input file.\n" "This program reads frames from a file, decodes them, and writes decoded\n" "video frames to a rawvideo file named video_output_file, and decoded\n" "audio frames to a rawaudio file named audio_output_file.\n\n" "If the -refcount option is specified, the program use the\n" "reference counting frame system which allows keeping a copy of\n" "the data for longer than one decode call.\n" "\n", argv[0]); exit(1); } if (argc == 5 && !strcmp(argv[1], "-refcount")) { refcount = 1; argv++; } src_filename = argv[1]; video_dst_filename = argv[2]; audio_dst_filename = argv[3]; /* open input file, and allocate format context */ if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) { fprintf(stderr, "Could not open source file %s\n", src_filename); exit(1); } /* retrieve stream information */ if (avformat_find_stream_info(fmt_ctx, NULL) < 0) { fprintf(stderr, "Could not find stream information\n"); exit(1); } if (open_codec_context(&video_stream_idx, &video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) { video_stream = fmt_ctx->streams[video_stream_idx]; video_dst_file = fopen(video_dst_filename, "wb"); if (!video_dst_file) { fprintf(stderr, "Could not open destination file %s\n", video_dst_filename); ret = 1; goto end; } /* allocate image where the decoded image will be put */ width = video_dec_ctx->width; height = video_dec_ctx->height; pix_fmt = video_dec_ctx->pix_fmt; ret = av_image_alloc(video_dst_data, video_dst_linesize, width, height, pix_fmt, 1); if (ret < 0) { fprintf(stderr, "Could not allocate raw video buffer\n"); goto end; } video_dst_bufsize = ret; } if (open_codec_context(&audio_stream_idx, &audio_dec_ctx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) { audio_stream = fmt_ctx->streams[audio_stream_idx]; audio_dst_file = fopen(audio_dst_filename, "wb"); if (!audio_dst_file) { fprintf(stderr, "Could not open destination file %s\n", audio_dst_filename); ret = 1; goto end; } } /* dump input information to stderr */ av_dump_format(fmt_ctx, 0, src_filename, 0); if (!audio_stream && !video_stream) { fprintf(stderr, "Could not find audio or video stream in the input, aborting\n"); ret = 1; goto end; } frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate frame\n"); ret = AVERROR(ENOMEM); goto end; } /* initialize packet, set data to NULL, let the demuxer fill it */ av_init_packet(&pkt); pkt.data = NULL; pkt.size = 0; if (video_stream) printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename); if (audio_stream) printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename); /* read frames from the file */ while (av_read_frame(fmt_ctx, &pkt) >= 0) { AVPacket orig_pkt = pkt; do { ret = decode_packet(&got_frame, 0); if (ret < 0) break; pkt.data += ret; pkt.size -= ret; } while (pkt.size > 0); av_packet_unref(&orig_pkt); } /* flush cached frames */ pkt.data = NULL; pkt.size = 0; do { decode_packet(&got_frame, 1); } while (got_frame); printf("Demuxing succeeded.\n"); if (video_stream) { printf("Play the output video file with the command:\n" "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n", av_get_pix_fmt_name(pix_fmt), width, height, video_dst_filename); } if (audio_stream) { enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt; int n_channels = audio_dec_ctx->channels; const char *fmt; if (av_sample_fmt_is_planar(sfmt)) { const char *packed = av_get_sample_fmt_name(sfmt); printf("Warning: the sample format the decoder produced is planar " "(%s). This example will output the first channel only.\n", packed ? packed : "?"); sfmt = av_get_packed_sample_fmt(sfmt); n_channels = 1; } if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0) goto end; printf("Play the output audio file with the command:\n" "ffplay -f %s -ac %d -ar %d %s\n", fmt, n_channels, audio_dec_ctx->sample_rate, audio_dst_filename); } end: avcodec_free_context(&video_dec_ctx); avcodec_free_context(&audio_dec_ctx); avformat_close_input(&fmt_ctx); if (video_dst_file) fclose(video_dst_file); if (audio_dst_file) fclose(audio_dst_file); av_frame_free(&frame); av_free(video_dst_data[0]); return ret < 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/encode_audio.c ================================================ /* * Copyright (c) 2001 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * audio encoding with libavcodec API example. * * @example encode_audio.c */ #include #include #include #include #include #include #include #include /* check that a given sample format is supported by the encoder */ static int check_sample_fmt(const AVCodec *codec, enum AVSampleFormat sample_fmt) { const enum AVSampleFormat *p = codec->sample_fmts; while (*p != AV_SAMPLE_FMT_NONE) { if (*p == sample_fmt) return 1; p++; } return 0; } /* just pick the highest supported samplerate */ static int select_sample_rate(const AVCodec *codec) { const int *p; int best_samplerate = 0; if (!codec->supported_samplerates) return 44100; p = codec->supported_samplerates; while (*p) { if (!best_samplerate || abs(44100 - *p) < abs(44100 - best_samplerate)) best_samplerate = *p; p++; } return best_samplerate; } /* select layout with the highest channel count */ static int select_channel_layout(const AVCodec *codec) { const uint64_t *p; uint64_t best_ch_layout = 0; int best_nb_channels = 0; if (!codec->channel_layouts) return AV_CH_LAYOUT_STEREO; p = codec->channel_layouts; while (*p) { int nb_channels = av_get_channel_layout_nb_channels(*p); if (nb_channels > best_nb_channels) { best_ch_layout = *p; best_nb_channels = nb_channels; } p++; } return best_ch_layout; } static void encode(AVCodecContext *ctx, AVFrame *frame, AVPacket *pkt, FILE *output) { int ret; /* send the frame for encoding */ ret = avcodec_send_frame(ctx, frame); if (ret < 0) { fprintf(stderr, "Error sending the frame to the encoder\n"); exit(1); } /* read all the available output packets (in general there may be any * number of them */ while (ret >= 0) { ret = avcodec_receive_packet(ctx, pkt); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) { fprintf(stderr, "Error encoding audio frame\n"); exit(1); } fwrite(pkt->data, 1, pkt->size, output); av_packet_unref(pkt); } } int main(int argc, char **argv) { const char *filename; const AVCodec *codec; AVCodecContext *c= NULL; AVFrame *frame; AVPacket *pkt; int i, j, k, ret; FILE *f; uint16_t *samples; float t, tincr; if (argc <= 1) { fprintf(stderr, "Usage: %s \n", argv[0]); return 0; } filename = argv[1]; /* find the MP2 encoder */ codec = avcodec_find_encoder(AV_CODEC_ID_MP2); if (!codec) { fprintf(stderr, "Codec not found\n"); exit(1); } c = avcodec_alloc_context3(codec); if (!c) { fprintf(stderr, "Could not allocate audio codec context\n"); exit(1); } /* put sample parameters */ c->bit_rate = 64000; /* check that the encoder supports s16 pcm input */ c->sample_fmt = AV_SAMPLE_FMT_S16; if (!check_sample_fmt(codec, c->sample_fmt)) { fprintf(stderr, "Encoder does not support sample format %s", av_get_sample_fmt_name(c->sample_fmt)); exit(1); } /* select other audio parameters supported by the encoder */ c->sample_rate = select_sample_rate(codec); c->channel_layout = select_channel_layout(codec); c->channels = av_get_channel_layout_nb_channels(c->channel_layout); /* open it */ if (avcodec_open2(c, codec, NULL) < 0) { fprintf(stderr, "Could not open codec\n"); exit(1); } f = fopen(filename, "wb"); if (!f) { fprintf(stderr, "Could not open %s\n", filename); exit(1); } /* packet for holding encoded output */ pkt = av_packet_alloc(); if (!pkt) { fprintf(stderr, "could not allocate the packet\n"); exit(1); } /* frame containing input raw audio */ frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate audio frame\n"); exit(1); } frame->nb_samples = c->frame_size; frame->format = c->sample_fmt; frame->channel_layout = c->channel_layout; /* allocate the data buffers */ ret = av_frame_get_buffer(frame, 0); if (ret < 0) { fprintf(stderr, "Could not allocate audio data buffers\n"); exit(1); } /* encode a single tone sound */ t = 0; tincr = 2 * M_PI * 440.0 / c->sample_rate; for (i = 0; i < 200; i++) { /* make sure the frame is writable -- makes a copy if the encoder * kept a reference internally */ ret = av_frame_make_writable(frame); if (ret < 0) exit(1); samples = (uint16_t*)frame->data[0]; for (j = 0; j < c->frame_size; j++) { samples[2*j] = (int)(sin(t) * 10000); for (k = 1; k < c->channels; k++) samples[2*j + k] = samples[2*j]; t += tincr; } encode(c, frame, pkt, f); } /* flush the encoder */ encode(c, NULL, pkt, f); fclose(f); av_frame_free(&frame); av_packet_free(&pkt); avcodec_free_context(&c); return 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/encode_video.c ================================================ /* * Copyright (c) 2001 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * @file * video encoding with libavcodec API example * * @example encode_video.c */ #include #include #include #include #include #include static void encode(AVCodecContext *enc_ctx, AVFrame *frame, AVPacket *pkt, FILE *outfile) { int ret; /* send the frame to the encoder */ if (frame) printf("Send frame %3"PRId64"\n", frame->pts); ret = avcodec_send_frame(enc_ctx, frame); if (ret < 0) { fprintf(stderr, "Error sending a frame for encoding\n"); exit(1); } while (ret >= 0) { ret = avcodec_receive_packet(enc_ctx, pkt); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) return; else if (ret < 0) { fprintf(stderr, "Error during encoding\n"); exit(1); } printf("Write packet %3"PRId64" (size=%5d)\n", pkt->pts, pkt->size); fwrite(pkt->data, 1, pkt->size, outfile); av_packet_unref(pkt); } } int main(int argc, char **argv) { const char *filename, *codec_name; const AVCodec *codec; AVCodecContext *c= NULL; int i, ret, x, y; FILE *f; AVFrame *frame; AVPacket *pkt; uint8_t endcode[] = { 0, 0, 1, 0xb7 }; if (argc <= 2) { fprintf(stderr, "Usage: %s \n", argv[0]); exit(0); } filename = argv[1]; codec_name = argv[2]; /* find the mpeg1video encoder */ codec = avcodec_find_encoder_by_name(codec_name); if (!codec) { fprintf(stderr, "Codec '%s' not found\n", codec_name); exit(1); } c = avcodec_alloc_context3(codec); if (!c) { fprintf(stderr, "Could not allocate video codec context\n"); exit(1); } pkt = av_packet_alloc(); if (!pkt) exit(1); /* put sample parameters */ c->bit_rate = 400000; /* resolution must be a multiple of two */ c->width = 352; c->height = 288; /* frames per second */ c->time_base = (AVRational){1, 25}; c->framerate = (AVRational){25, 1}; /* emit one intra frame every ten frames * check frame pict_type before passing frame * to encoder, if frame->pict_type is AV_PICTURE_TYPE_I * then gop_size is ignored and the output of encoder * will always be I frame irrespective to gop_size */ c->gop_size = 10; c->max_b_frames = 1; c->pix_fmt = AV_PIX_FMT_YUV420P; if (codec->id == AV_CODEC_ID_H264) av_opt_set(c->priv_data, "preset", "slow", 0); /* open it */ ret = avcodec_open2(c, codec, NULL); if (ret < 0) { fprintf(stderr, "Could not open codec: %s\n", av_err2str(ret)); exit(1); } f = fopen(filename, "wb"); if (!f) { fprintf(stderr, "Could not open %s\n", filename); exit(1); } frame = av_frame_alloc(); if (!frame) { fprintf(stderr, "Could not allocate video frame\n"); exit(1); } frame->format = c->pix_fmt; frame->width = c->width; frame->height = c->height; ret = av_frame_get_buffer(frame, 32); if (ret < 0) { fprintf(stderr, "Could not allocate the video frame data\n"); exit(1); } /* encode 1 second of video */ for (i = 0; i < 25; i++) { fflush(stdout); /* make sure the frame data is writable */ ret = av_frame_make_writable(frame); if (ret < 0) exit(1); /* prepare a dummy image */ /* Y */ for (y = 0; y < c->height; y++) { for (x = 0; x < c->width; x++) { frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3; } } /* Cb and Cr */ for (y = 0; y < c->height/2; y++) { for (x = 0; x < c->width/2; x++) { frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2; frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5; } } frame->pts = i; /* encode the image */ encode(c, frame, pkt, f); } /* flush the encoder */ encode(c, NULL, pkt, f); /* add sequence end code to have a real MPEG file */ fwrite(endcode, 1, sizeof(endcode), f); fclose(f); avcodec_free_context(&c); av_frame_free(&frame); av_packet_free(&pkt); return 0; } ================================================ FILE: ThirdParty/ffmpeg/examples/extract_mvs.c ================================================ /* * Copyright (c) 2012 Stefano Sabatini * Copyright (c) 2014 Clément Bœsch * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include #include static AVFormatContext *fmt_ctx = NULL; static AVCodecContext *video_dec_ctx = NULL; static AVStream *video_stream = NULL; static const char *src_filename = NULL; static int video_stream_idx = -1; static AVFrame *frame = NULL; static int video_frame_count = 0; static int decode_packet(const AVPacket *pkt) { int ret = avcodec_send_packet(video_dec_ctx, pkt); if (ret < 0) { fprintf(stderr, "Error while sending a packet to the decoder: %s\n", av_err2str(ret)); return ret; } while (ret >= 0) { ret = avcodec_receive_frame(video_dec_ctx, frame); if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) { break; } else if (ret < 0) { fprintf(stderr, "Error while receiving a frame from the decoder: %s\n", av_err2str(ret)); return ret; } if (ret >= 0) { int i; AVFrameSideData *sd; video_frame_count++; sd = av_frame_get_side_data(frame, AV_FRAME_DATA_MOTION_VECTORS); if (sd) { const AVMotionVector *mvs = (const AVMotionVector *)sd->data; for (i = 0; i < sd->size / sizeof(*mvs); i++) { const AVMotionVector *mv = &mvs[i]; printf("%d,%2d,%2d,%2d,%4d,%4d,%4d,%4d,0x%"PRIx64"\n", video_frame_count, mv->source, mv->w, mv->h, mv->src_x, mv->src_y, mv->dst_x, mv->dst_y, mv->flags); } } av_frame_unref(frame); } } return 0; } static int open_codec_context(AVFormatContext *fmt_ctx, enum AVMediaType type) { int ret; AVStream *st; AVCodecContext *dec_ctx = NULL; AVCodec *dec = NULL; AVDictionary *opts = NULL; ret = av_find_best_stream(fmt_ctx, type, -1, -1, &dec, 0); if (ret < 0) { fprintf(stderr, "Could not find %s stream in input file '%s'\n", av_get_media_type_string(type), src_filename); return ret; } else { int stream_idx = ret; st = fmt_ctx->streams[stream_idx]; dec_ctx = avcodec_alloc_context3(dec); if (!dec_ctx) { fprintf(stderr, "Failed to allocate codec\n"); return AVERROR(EINVAL); } ret = avcodec_parameters_to_context(dec_ctx, st->codecpar); if (ret < 0) { fprintf(stderr, "Failed to copy codec parameters to codec context\n"); return ret; } /* Init the video decoder */ av_dict_set(&opts, "flags2", "+export_mvs", 0); if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) { fprintf(stderr, "Failed to open %s codec\n", av_get_media_type_string(type)); return ret; } video_stream_idx = stream_idx; video_stream = fmt_ctx->streams[video_stream_idx]; video_dec_ctx = dec_ctx; } return 0; } int main(int argc, char **argv) { int ret = 0; AVPacket pkt = { 0 }; if (argc != 2) { fprintf(stderr, "Usage: %s