diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4432d77 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,54 @@ +# AGENTS.md — rusty-telemetry Project Context + +## Mandatory Reference + +**Before starting any work on this project, always read the Joplin note that contains the full project plan and architecture.** + +- **Joplin Note ID**: `6c0dcb2a567348fd9796f50c790082e4` +- **Title**: "Sim Racing Telemetry Analysis Platform — Project Plan" +- **Tags**: sim-racing, lua, telemetry, rust, project-plan, assetto-corsa + +Use the `joplin_get_note` tool with note ID `6c0dcb2a567348fd9796f50c790082e4` to retrieve the full project plan. + +## Project Overview + +`rusty-telemetry` is a Rust-based multi-port UDP telemetry listener and analysis platform for sim racing. It receives telemetry from Assetto Corsa (KSUDP + Telemetry Tool) and Project CARS 1 & 2, provides a terminal dashboard (ratatui), and exposes a REST API for session management, analysis, and car characteristics aggregation. + +## Companion Repository + +| Field | Value | +|-------|-------| +| **Repo** | `racecraft` | +| **Path** | `~/WebstormProjects/racecraft` | +| **Language** | TypeScript (Vue 3) | +| **Purpose** | Web client — live telemetry, session UI, charts, track maps | + +## Tech Stack + +- Rust (edition 2021) +- Tokio (async runtime) +- Axum 0.8 (REST API) +- Ratatui (terminal UI) +- Serde (JSON serialization) + +## Key Ports + +| Port | Feed Name | Source | Format | +|-------|-------------------|-------------------------------|---------| +| 9996 | ksudp | AC built-in engine | Binary (3-phase handshake, RTCarInfo) | +| 10101 | telemetry_tool | Telemetry Tool Python plugin | Binary (per-driver structs, ~60 Hz) | +| 5606 | pcars | Project CARS 1 & 2 | Binary (V1 1367B / V2 559B, auto-detected) | +| 8080 | REST API | Axum HTTP server | JSON | + +## Data Persistence + +- **Recordings**: `./data//` — manifest.json + per-feed JSONL files (written on shutdown) +- **Sessions**: `./data/sessions/.json` (metadata + analysis) + `.frames.json` (frames, lazy-loaded) +- **Track Models**: stored in session analysis results, served via `/api/tracks` + +## Commands + +```bash +cargo run --release # Start server + TUI +cargo test # Run 33 unit tests +``` diff --git a/COMMERCIAL_LICENSE.md b/COMMERCIAL_LICENSE.md new file mode 100644 index 0000000..e81da74 --- /dev/null +++ b/COMMERCIAL_LICENSE.md @@ -0,0 +1,33 @@ +# Commercial License + +This software is dual-licensed: + +1. **GNU AGPL-3.0** — for open-source use, self-hosting, and community contributions +2. **Commercial License** — for use cases that require avoiding AGPL obligations + +## When you need a commercial license + +You need a commercial license if your use case involves any of the following and you do not want to release your modifications under AGPL-3.0: + +- **Self-hosting a modified version** at a venue or organization (e.g., karting tracks, sim racing centers) +- **Embedding or bundling** this software into hardware products (e.g., data loggers, OBD-II devices, telemetry hardware) +- **Offering a modified version as a network service** (the AGPL-3.0 §13 network-use clause requires sharing all modifications if you don't have a commercial license) +- **Distributing modified versions** without releasing source code + +## When you do NOT need a commercial license + +- Personal, non-commercial use (e.g., analyzing your own sim racing telemetry) +- Studying, modifying, or contributing to the open-source project +- Self-hosting an unmodified version for personal use +- Any use where you are comfortable releasing modifications under AGPL-3.0 + +## Contact + +For commercial license inquiries, pricing, and terms: + +**Jan-Peter v. Hunnius** +Email: jan@hunnius.net + +## Contributor License Agreement + +External contributors must sign a Contributor License Agreement (CLA) before their contributions can be merged. This ensures the project maintainer retains the right to offer commercial licenses. The CLA grants the maintainer a perpetual, worldwide, non-exclusive license to use, modify, and sublicense the contribution under any license. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md index 3bb5850..d9913fe 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Multi-port UDP telemetry listener and analysis platform for sim racing games. -Receives real-time telemetry from **Assetto Corsa** and **Project CARS 1 & 2** via UDP, parses binary packet formats, and provides live data via a terminal dashboard and REST API. Supports use-case driven analysis sessions for shift point optimization and track mapping. +Receives real-time telemetry from **Assetto Corsa** and **Project CARS 1 & 2** via UDP, parses binary packet formats, and provides live data via a terminal dashboard and REST API. Supports use-case driven analysis sessions for shift point optimization and track mapping, with persistent session storage and cross-session car characteristics aggregation. ## Supported Games @@ -147,14 +147,22 @@ Each recording has a `manifest.json` with metadata (game, track, car, use case, Use-case sessions allow targeted data capture and analysis: -1. **Create a session** with a use case (`shift_points` or `track_map`) +1. **Create a session** with a use case (`shift_points` or `track_mapping`) 2. **Start runs** — each run captures frames from the ring buffer between start and stop 3. **Complete the session** — auto-analyzes captured data and stores results 4. **Retrieve analysis** — shift point RPM ranges or track boundary coordinates 5. **Re-open if needed** — re-open a completed session to add more runs, then complete again 6. **Delete runs** — remove unwanted runs from a session (must be stopped first) -Sessions are in-memory and independent of persistent recordings. +Sessions are persistent: session metadata, runs, and analysis results survive a restart. On startup, all sessions are loaded from disk and incomplete runs are normalized to stopped state. Session data is stored separately from recordings: + +``` +./data/sessions/ +├── .json # Metadata (runs, analysis results, car_name) +└── .frames.json # Telemetry frames (lazy-loaded on demand) +``` + +Session metadata is loaded at startup for fast listing; frame data is lazy-loaded only when analysis or frame extraction is requested. Writes are atomic (temp file + rename) and frame serialization is offloaded to a background thread to avoid blocking the API. #### Feed Merging @@ -193,8 +201,7 @@ A built-in HTTP API server runs on port 8080 for recording management and live t | POST | `/api/recordings/{id}/stop` | Stop specific recording | | DELETE | `/api/recordings/{id}` | Delete recording | | GET | `/api/recordings/{id}/data/{feed_name}` | Download raw feed JSONL | -| GET | `/api/use-cases` | List valid use cases | -| GET | `/api/games` | List supported games | +| GET | `/api/use-cases` | List valid use cases || GET | `/api/games` | List supported games | | GET | `/api/sessions` | List all sessions | | POST | `/api/sessions` | Create analysis session | | GET | `/api/sessions/{id}` | Get session details | @@ -206,6 +213,11 @@ A built-in HTTP API server runs on port 8080 for recording management and live t | POST | `/api/sessions/{id}/complete` | Complete session + auto-analyze | | GET | `/api/sessions/{id}/analysis` | Get analysis results | | POST | `/api/sessions/{id}/analyze` | Re-run analysis on completed session | +| GET | `/api/characteristics/cars` | List all cars with aggregated shift-point data | +| GET | `/api/characteristics/cars/{car}` | Get detailed shift-point profile for a car | +| GET | `/api/tracks` | List all track models | +| GET | `/api/tracks/{track}` | Get a track model by key | +| POST | `/api/tracks/build` | Build a track model from a completed track_mapping session | ### Start Recording Body @@ -289,7 +301,8 @@ Returns the updated session on success. ```json [ { "id": "shift_points", "name": "ShiftPoints", "guidance": "1. Drive to a long straight..." }, - { "id": "track_map", "name": "TrackMap", "guidance": "1. Drive a complete lap..." } + { "id": "car_grip", "name": "CarGrip", "guidance": "Drive 3-5 laps at race pace..." }, + { "id": "track_mapping", "name": "TrackMapping", "guidance": "1. Drive a complete lap..." } ] ``` @@ -298,6 +311,70 @@ Each object contains: - `name` — human-readable name - `guidance` — step-by-step instructions for the use case +### Car Characteristics + +The characteristics endpoints aggregate shift-point analysis data across all completed `shift_points` sessions for each car. This provides a growing database of optimal shift RPMs per gear, useful for comparing setups and tracking improvements over time. + +**`GET /api/characteristics/cars`** — returns a summary list: + +```json +[ + { + "car_name": "Ferrari 488 GT3", + "session_count": 3, + "recommended_shift_rpm": 7500.0 + } +] +``` + +**`GET /api/characteristics/cars/{car}`** — returns detailed per-gear data: + +```json +{ + "car_name": "Ferrari 488 GT3", + "gears": [ + { + "gear": 2, + "min_rpm": 3200, + "max_rpm": 8500, + "min_speed_kmh": 45.0, + "max_speed_kmh": 120.0 + } + ], + "recommended_shift_rpm": 7500.0, + "session_count": 3 +} +``` + +### Car Grip Analysis Response + +Produced by the `car_grip` use case. The analysis uses **envelope extraction** — for each 10 km/h speed bin, it finds the peak |lateral G|, peak acceleration G, and peak braking G. This builds the grip limit curve from whatever data you provide; the harder you drive, the more complete the profile. + +```json +{ + "summary": { + "max_lateral_g": 1.42, + "max_accel_g": 0.85, + "max_brake_g": 1.35, + "max_combined_g": 1.58, + "peak_lateral_speed_kmh": 120.0 + }, + "grip_envelope": [ + { "speed_kmh": 45.0, "max_lateral_g": 1.2, "max_accel_g": 0.8, "max_brake_g": 1.1, "sample_count": 340 } + ], + "grip_circle": [ + { "longitudinal_g": 0.5, "lateral_g": -1.2 } + ], + "steering_response": [ + { "steer": 0.15, "lateral_g": -1.1, "speed_kmh": 95.0 } + ], + "runs_analyzed": 3, + "total_frames_analyzed": 8400 +} +``` + +The `grip_envelope` array has one entry per populated speed bin. The `grip_circle` and `steering_response` arrays are downsampled scatter points (~800 each) for chart rendering. + ### Shift Point Analysis Response ```json @@ -353,7 +430,7 @@ Then start the web client on the same machine — it proxies `/api/*` to `localh cargo test ``` -32 unit tests covering: +33 unit tests covering: - Binary parsers for all three feed formats (KSUDP, Telemetry Tool, PCARS V1/V2) - Ring buffer frequency calculation and edge cases - Feed health state machine transitions (Waiting → Alive → Stale → Alive) @@ -364,10 +441,12 @@ cargo test ``` src/ ├── main.rs Multi-port UDP listener, TUI event loop, KSUDP handshake -├── api.rs REST API server (axum) — recordings, sessions, live telemetry +├── api.rs REST API server (axum) — recordings, sessions, tracks, characteristics, live telemetry ├── recording.rs Recording manager — ring buffers, manifest CRUD, flush to JSONL -├── session.rs Session manager — use-case sessions, runs, frame extraction +├── session.rs Session manager — persistent sessions, runs, frame extraction, lazy-loading ├── analysis.rs Analysis algorithms — shift points, track mapping +├── characteristics.rs Car characteristics aggregation — cross-session shift-point profiles +├── track_model.rs Track model geometry — center line computation, boundary data ├── binary_utils.rs Shared safe binary read helpers (bounds-checked, zero fallback) ├── telemetry_frame.rs Unified telemetry data model (TelemetryFrame) ├── feed_state.rs Per-feed health/frequency state machine with ring buffer diff --git a/src/analysis.rs b/src/analysis.rs index dd0de4c..074c5e4 100644 --- a/src/analysis.rs +++ b/src/analysis.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Telemetry analysis algorithms for sim racing data. //! //! Provides shift point analysis, track map reconstruction, and a dispatch @@ -8,6 +23,75 @@ use std::collections::HashMap; use crate::recording::UseCase; use crate::telemetry_frame::{gear_display, TelemetryFrame}; +use crate::track_model::{Corner, Sector, TrackModel, TrackModelSource}; + +// --------------------------------------------------------------------------- +// Frame trimming utilities +// --------------------------------------------------------------------------- + +/// Split a run's frames into segments by lap_count transitions. +fn split_by_lap(frames: &[TelemetryFrame]) -> Vec<&[TelemetryFrame]> { + if frames.is_empty() { + return Vec::new(); + } + let mut segments = Vec::new(); + let mut seg_start = 0; + let mut prev_lap = frames[0].lap_count; + for (i, f) in frames.iter().enumerate() { + if f.lap_count != prev_lap { + segments.push(&frames[seg_start..i]); + seg_start = i; + prev_lap = f.lap_count; + } + } + segments.push(&frames[seg_start..]); + segments +} + +/// Return frames belonging to complete laps only. +/// +/// A complete lap covers most of the track (spline spans ≥ 0.9 of [0, 1]). +/// The first segment may start mid-track (driver joined before start/finish) +/// but still complete a full revolution — spline wraps from the join point +/// through 1.0 back to near 0. The last segment is often a partial out-lap +/// (driver stopped before completing the lap). +fn complete_lap_frames(frames: &[TelemetryFrame]) -> Vec { + let segments = split_by_lap(frames); + if segments.is_empty() { + return frames.to_vec(); + } + + let mut result = Vec::new(); + for seg in &segments { + let splines: Vec = seg.iter().filter(|f| f.spline_position > 0.0).map(|f| f.spline_position).collect(); + if splines.is_empty() { + continue; + } + let min_s = splines.iter().cloned().fold(f32::INFINITY, f32::min); + let max_s = splines.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let span = max_s - min_s; + // Complete lap: spline covers ≥ 0.9 of the track, or wraps around + // (min near 0, max near 1). + let wraps = min_s < 0.1 && max_s > 0.9; + if span >= 0.9 || wraps { + result.extend_from_slice(seg); + } + } + + // If no segment qualifies (e.g., no spline data), fall back to longest. + if result.is_empty() { + let longest = segments.iter().max_by_key(|s| s.len()); + if let Some(seg) = longest { + return seg.to_vec(); + } + } + + if result.is_empty() { + frames.to_vec() + } else { + result + } +} // --------------------------------------------------------------------------- // Shift Point Analysis @@ -64,9 +148,28 @@ pub fn analyze_shift_points( for (run_idx, run) in runs.iter().enumerate() { let label = run_labels.get(run_idx).cloned().unwrap_or_default(); - let valid: Vec<&TelemetryFrame> = run + // Trim to the WOT window: find the first and last frames where + // throttle is near 100%. This removes pre-launch and post-lift data. + let wot_start = run.iter().position(|f| f.throttle >= 0.9); + let wot_end = run.iter().rposition(|f| f.throttle >= 0.9); + let trimmed: &[TelemetryFrame] = match (wot_start, wot_end) { + (Some(s), Some(e)) if e > s => &run[s..=e], + _ => run.as_slice(), + }; + + // Filter for valid WOT acceleration frames. + // Exclude rev-limiter plateau: when speed stops increasing (delta < 0.5 km/h + // over the window), the engine is bouncing off the limiter and acceleration + // data is meaningless. + let valid: Vec<&TelemetryFrame> = trimmed .iter() - .filter(|f| f.throttle >= 0.9 && f.gear >= 2 && f.speed_kmh > 1.0 && f.engine_rpm > 500.0) + .filter(|f| { + f.throttle >= 0.9 + && f.gear >= 2 + && f.speed_kmh > 1.0 + && f.engine_rpm > 500.0 + && f.acc_g_frontal > 0.01 + }) .collect(); if valid.len() < 10 { @@ -100,7 +203,7 @@ pub fn analyze_shift_points( points.sort_by(|a, b| a.speed_kmh.partial_cmp(&b.speed_kmh).unwrap_or(std::cmp::Ordering::Equal)); - let window = (points.len() / 5).max(3).min(15); + let window = (points.len() / 5).clamp(3, 15); let acc_values: Vec = points.iter().map(|p| p.acceleration_g).collect(); let smoothed = smooth(&acc_values, window); @@ -161,7 +264,7 @@ fn smooth(values: &[f32], window: usize) -> Vec { let n = values.len(); let mut result = Vec::with_capacity(n); for i in 0..n { - let start = if i >= half { i - half } else { 0 }; + let start = i.saturating_sub(half); let end = (i + half + 1).min(n); let sum: f32 = values[start..end].iter().sum(); result.push(sum / (end - start) as f32); @@ -276,7 +379,44 @@ fn lerp_search( // Track Map Analysis // --------------------------------------------------------------------------- -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, serde::Deserialize, PartialEq)] +pub enum PositionMode { + Spline, + Coordinate, +} + +fn detect_position_mode(frames: &[TelemetryFrame]) -> PositionMode { + if frames.is_empty() { + return PositionMode::Coordinate; + } + let with_spline = frames.iter().filter(|f| f.spline_position > 0.0).count(); + let spline_ratio = with_spline as f32 / frames.len() as f32; + if spline_ratio > 0.5 { + PositionMode::Spline + } else { + PositionMode::Coordinate + } +} + +fn compute_cumulative_distance(points: &mut [TrackPoint]) { + if points.is_empty() { return; } + let mut cumulative = 0.0f32; + points[0].spline = 0.0; + for i in 1..points.len() { + let dx = points[i].x - points[i-1].x; + let dz = points[i].z - points[i-1].z; + cumulative += (dx * dx + dz * dz).sqrt(); + points[i].spline = cumulative; + } + if cumulative > 0.0 { + for p in points.iter_mut() { + p.spline /= cumulative; + } + } +} + + +#[derive(Debug, Clone, Serialize, serde::Deserialize)] pub struct TrackPoint { pub x: f32, pub y: f32, @@ -284,7 +424,7 @@ pub struct TrackPoint { pub spline: f32, } -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, serde::Deserialize)] pub struct TrackBoundary { pub label: String, pub point_count: usize, @@ -296,26 +436,56 @@ pub struct TrackMapAnalysis { pub boundaries: Vec, pub center_line: Option, pub total_points: usize, + pub position_mode: PositionMode, } pub fn analyze_track_map( runs: &[Vec], labels: &[String], ) -> TrackMapAnalysis { + let all_frames: Vec = runs.iter().flat_map(|r| r.iter()).cloned().collect(); + let mode = detect_position_mode(&all_frames); + let mut boundaries: Vec = Vec::new(); for (run, label) in runs.iter().zip(labels.iter()) { - let mut points: Vec = run - .iter() - .filter(|f| f.spline_position != 0.0) - .map(|f| TrackPoint { - x: f.world_x, - y: f.world_y, - z: f.world_z, - spline: f.spline_position, - }) - .collect(); + // Trim to complete laps only — partial laps at the start/end of + // the recording produce artifacts when spline-sorted (the car + // was not at the boundary edge during those segments). + let trimmed = complete_lap_frames(run); + + let mut points: Vec = match &mode { + PositionMode::Spline => { + trimmed + .iter() + .filter(|f| f.spline_position > 0.0) + .map(|f| TrackPoint { + x: f.world_x, + y: f.world_y, + z: f.world_z, + spline: f.spline_position, + }) + .collect() + } + PositionMode::Coordinate => { + let mut pts: Vec = trimmed + .iter() + .filter(|f| f.world_x != 0.0 || f.world_z != 0.0) + .map(|f| TrackPoint { + x: f.world_x, + y: f.world_y, + z: f.world_z, + spline: 0.0, + }) + .collect(); + compute_cumulative_distance(&mut pts); + pts + } + }; + points.sort_by(|a, b| a.spline.partial_cmp(&b.spline).unwrap_or(std::cmp::Ordering::Equal)); + points.dedup_by(|a, b| (a.spline - b.spline).abs() < 0.0001); + let point_count = points.len(); boundaries.push(TrackBoundary { label: label.clone(), @@ -333,6 +503,7 @@ pub fn analyze_track_map( boundaries, center_line, total_points, + position_mode: mode, } } @@ -397,6 +568,629 @@ fn interpolate_boundary(boundary: &TrackBoundary, target_spline: f32) -> Option< }) } + +// --------------------------------------------------------------------------- +// Track Model Builder +// --------------------------------------------------------------------------- + +const NUM_SAMPLES: usize = 2000; +const CORNER_THRESHOLD: f64 = 0.005; + + + + +pub fn build_track_model( + boundaries: &[TrackBoundary], + game: String, + track_name: String, + source: TrackModelSource, +) -> Result { + // Step 1: Validate input + if boundaries.len() != 2 { + return Err(format!( + "Expected exactly 2 boundaries, got {}", + boundaries.len() + )); + } + + let left_idx = boundaries + .iter() + .position(|b| b.label == "left") + .ok_or_else(|| "No boundary labeled 'left' found".to_string())?; + let right_idx = boundaries + .iter() + .position(|b| b.label == "right") + .ok_or_else(|| "No boundary labeled 'right' found".to_string())?; + + let left = &boundaries[left_idx]; + let right = &boundaries[right_idx]; + + if left.points.len() < 10 { + return Err(format!( + "Left boundary needs at least 10 points, has {}", + left.points.len() + )); + } + if right.points.len() < 10 { + return Err(format!( + "Right boundary needs at least 10 points, has {}", + right.points.len() + )); + } + + // Step 2: Resample both boundaries + let left_resampled: Vec<(f64, f64)> = (0..NUM_SAMPLES) + .map(|i| { + let s = i as f32 / (NUM_SAMPLES - 1) as f32; + let p = interpolate_boundary(left, s).expect("interpolation within range"); + (p.x as f64, p.z as f64) + }) + .collect(); + + let right_resampled: Vec<(f64, f64)> = (0..NUM_SAMPLES) + .map(|i| { + let s = i as f32 / (NUM_SAMPLES - 1) as f32; + let p = interpolate_boundary(right, s).expect("interpolation within range"); + (p.x as f64, p.z as f64) + }) + .collect(); + + // Step 3: Compute center line + let center_line: Vec<(f64, f64)> = left_resampled + .iter() + .zip(right_resampled.iter()) + .map(|((lx, lz), (rx, rz))| ((lx + rx) / 2.0, (lz + rz) / 2.0)) + .collect(); + + // Step 4: Compute track width + let track_width: Vec = left_resampled + .iter() + .zip(right_resampled.iter()) + .map(|((lx, lz), (rx, rz))| { + let dx = rx - lx; + let dz = rz - lz; + (dx * dx + dz * dz).sqrt() + }) + .collect(); + + // Step 5: Compute heading + let mut heading: Vec = Vec::with_capacity(NUM_SAMPLES); + for i in 0..center_line.len() - 1 { + let dx = center_line[i + 1].0 - center_line[i].0; + let dz = center_line[i + 1].1 - center_line[i].1; + heading.push(dz.atan2(dx)); + } + heading.push(*heading.last().unwrap_or(&0.0)); + + // Step 6: Compute curvature + let mut curvature: Vec = Vec::with_capacity(NUM_SAMPLES); + for i in 0..center_line.len() - 1 { + let dx = center_line[i + 1].0 - center_line[i].0; + let dz = center_line[i + 1].1 - center_line[i].1; + let ds = (dx * dx + dz * dz).sqrt().max(1e-10); + let mut dtheta = heading[i + 1] - heading[i]; + // Normalize to [-π, π] + while dtheta > std::f64::consts::PI { + dtheta -= 2.0 * std::f64::consts::PI; + } + while dtheta < -std::f64::consts::PI { + dtheta += 2.0 * std::f64::consts::PI; + } + curvature.push(dtheta / ds); + } + curvature.push(0.0); + + // Step 7: Smooth curvature + let window = (curvature.len() / 50).clamp(3, 21); + let smoothed_curvature = smooth_f64(&curvature, window); + + // Step 8: Auto-detect corners + let corners = detect_corners(&smoothed_curvature); + + // Step 9: Define sectors + let sectors = vec![ + Sector { + index: 0, + start_s: 0.0, + end_s: 1.0 / 3.0, + }, + Sector { + index: 1, + start_s: 1.0 / 3.0, + end_s: 2.0 / 3.0, + }, + Sector { + index: 2, + start_s: 2.0 / 3.0, + end_s: 1.0, + }, + ]; + + // Step 10: Normalize coordinates using bounds from all arrays + let mut min_x = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut min_z = f64::INFINITY; + let mut max_z = f64::NEG_INFINITY; + + for (x, z) in center_line.iter().chain(left_resampled.iter()).chain(right_resampled.iter()) { + min_x = min_x.min(*x); + max_x = max_x.max(*x); + min_z = min_z.min(*z); + max_z = max_z.max(*z); + } + + let scale = (max_x - min_x).max(max_z - min_z).max(1e-6); + + let normalize = |px: f64, pz: f64| -> (f64, f64) { ((px - min_x) / scale, (pz - min_z) / scale) }; + + let normalized_center: Vec<(f64, f64)> = center_line + .into_iter() + .map(|(x, z)| normalize(x, z)) + .collect(); + let normalized_left: Vec<(f64, f64)> = left_resampled + .into_iter() + .map(|(x, z)| normalize(x, z)) + .collect(); + let normalized_right: Vec<(f64, f64)> = right_resampled + .into_iter() + .map(|(x, z)| normalize(x, z)) + .collect(); + + // Step 11: Build and return TrackModel + Ok(TrackModel { + game, + track_name, + center_line: normalized_center, + left_boundary: normalized_left, + right_boundary: normalized_right, + track_width, + heading, + curvature: smoothed_curvature, + corners, + sectors, + source, + created_at: chrono::Utc::now().to_rfc3339(), + }) +} + +fn smooth_f64(values: &[f64], window: usize) -> Vec { + let half = window / 2; + let n = values.len(); + let mut result = Vec::with_capacity(n); + for i in 0..n { + let start = i.saturating_sub(half); + let end = (i + half + 1).min(n); + let sum: f64 = values[start..end].iter().sum(); + result.push(sum / (end - start) as f64); + } + result +} + +fn detect_corners(curvature: &[f64]) -> Vec { + let mut corners = Vec::new(); + let mut in_corner = false; + let mut corner_start_s = 0.0f64; + let mut peak_idx = 0usize; + let mut peak_kappa = 0.0f64; + + let len = curvature.len(); + let denom = (len - 1).max(1) as f64; + + for (i, &k) in curvature.iter().enumerate() { + let abs_k = k.abs(); + if abs_k > CORNER_THRESHOLD && !in_corner { + in_corner = true; + corner_start_s = i.saturating_sub(5) as f64 / denom; + peak_idx = i; + peak_kappa = abs_k; + } else if abs_k > peak_kappa && in_corner { + peak_idx = i; + peak_kappa = abs_k; + } else if abs_k <= CORNER_THRESHOLD * 0.5 && in_corner { + in_corner = false; + let corner_end = (i + 5).min(len - 1); + let apex_s = peak_idx as f64 / denom; + let exit_s = corner_end as f64 / denom; + + if exit_s - corner_start_s > 0.005 { + corners.push(Corner { + index: peak_idx, + number: 0, + entry_s: corner_start_s, + apex_s, + exit_s, + curvature_peak: peak_kappa, + }); + } + } + } + + if in_corner { + let apex_s = peak_idx as f64 / denom; + corners.push(Corner { + index: peak_idx, + number: 0, + entry_s: corner_start_s, + apex_s, + exit_s: 1.0, + curvature_peak: peak_kappa, + }); + } + + for (i, corner) in corners.iter_mut().enumerate() { + corner.number = (i + 1) as u32; + } + + corners +} +// --------------------------------------------------------------------------- +// Car Grip Analysis (envelope extraction) +// --------------------------------------------------------------------------- + +/// Speed bin width for the grip envelope (km/h). +const GRIP_SPEED_BIN: f32 = 10.0; +/// Maximum speed bin center (km/h). +const GRIP_MAX_SPEED: f32 = 360.0; +/// Target number of downsampled scatter points per dataset. +const GRIP_SCATTER_TARGET: usize = 800; + +#[derive(Debug, Clone, Serialize)] +pub struct GripEnvelopePoint { + pub speed_kmh: f32, + pub max_lateral_g: f32, + pub max_accel_g: f32, + pub max_brake_g: f32, + pub sample_count: usize, +} + +#[derive(Debug, Clone, Serialize)] +pub struct GripCirclePoint { + pub longitudinal_g: f32, + pub lateral_g: f32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct SteeringResponsePoint { + pub steer: f32, + pub lateral_g: f32, + pub speed_kmh: f32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct GripSummary { + pub max_lateral_g: f32, + pub max_accel_g: f32, + pub max_brake_g: f32, + pub max_combined_g: f32, + pub peak_lateral_speed_kmh: f32, +} + +#[derive(Debug, Clone, Serialize)] +pub struct CarGripAnalysis { + pub summary: GripSummary, + pub grip_envelope: Vec, + pub grip_circle: Vec, + pub steering_response: Vec, + pub runs_analyzed: usize, + pub total_frames_analyzed: usize, +} + +pub fn analyze_car_grip(runs: &[Vec]) -> CarGripAnalysis { + let num_bins = (GRIP_MAX_SPEED / GRIP_SPEED_BIN) as usize; + + // Per-bin trackers: (max_lat, max_accel, max_brake, count) + let mut bins: Vec<(f32, f32, f32, usize)> = vec![(0.0, 0.0, 0.0, 0); num_bins]; + + // Scatter accumulators (before downsampling) + let mut circle_raw: Vec = Vec::new(); + let mut steer_raw: Vec = Vec::new(); + + // Summary trackers + let mut max_lat = 0.0f32; + let mut max_lat_speed = 0.0f32; + let mut max_accel = 0.0f32; + let mut max_brake = 0.0f32; + let mut max_combined = 0.0f32; + + let mut total_frames: usize = 0; + let mut runs_analyzed: usize = 0; + + for run in runs { + if run.is_empty() { + continue; + } + runs_analyzed += 1; + + for f in run { + // Filter: skip pit, very low speed + if f.is_in_pit || f.speed_kmh < 5.0 { + continue; + } + + let lat = f.acc_g_horizontal.abs(); + let long = f.acc_g_frontal; + let accel = if long > 0.0 { long } else { 0.0 }; + let brake = if long < 0.0 { long.abs() } else { 0.0 }; + let combined = (lat * lat + long * long).sqrt(); + + total_frames += 1; + + // Update summary + if lat > max_lat { + max_lat = lat; + max_lat_speed = f.speed_kmh; + } + if accel > max_accel { + max_accel = accel; + } + if brake > max_brake { + max_brake = brake; + } + if combined > max_combined { + max_combined = combined; + } + + // Update speed bin + let bin_idx = ((f.speed_kmh / GRIP_SPEED_BIN) as usize).min(num_bins - 1); + let b = &mut bins[bin_idx]; + b.0 = b.0.max(lat); + b.1 = b.1.max(accel); + b.2 = b.2.max(brake); + b.3 += 1; + + // Accumulate scatter points (only for significant cornering/braking) + if lat > 0.3 || long.abs() > 0.3 { + circle_raw.push(GripCirclePoint { + longitudinal_g: long, + lateral_g: f.acc_g_horizontal, + }); + } + if f.steer.abs() > 0.02 && lat > 0.1 { + steer_raw.push(SteeringResponsePoint { + steer: f.steer, + lateral_g: f.acc_g_horizontal, + speed_kmh: f.speed_kmh, + }); + } + } + } + + // Build envelope from bins (only include bins with data) + let grip_envelope: Vec = bins + .iter() + .enumerate() + .filter(|(_, b)| b.3 > 0) + .map(|(i, b)| GripEnvelopePoint { + speed_kmh: i as f32 * GRIP_SPEED_BIN + GRIP_SPEED_BIN / 2.0, + max_lateral_g: b.0, + max_accel_g: b.1, + max_brake_g: b.2, + sample_count: b.3, + }) + .collect(); + + let grip_circle = downsample(circle_raw, GRIP_SCATTER_TARGET); + let steering_response = downsample(steer_raw, GRIP_SCATTER_TARGET); + + CarGripAnalysis { + summary: GripSummary { + max_lateral_g: max_lat, + max_accel_g: max_accel, + max_brake_g: max_brake, + max_combined_g: max_combined, + peak_lateral_speed_kmh: max_lat_speed, + }, + grip_envelope, + grip_circle, + steering_response, + runs_analyzed, + total_frames_analyzed: total_frames, + } +} + +fn downsample(items: Vec, target: usize) -> Vec { + if items.len() <= target { + return items; + } + let step = items.len() as f32 / target as f32; + let mut result = Vec::with_capacity(target); + let mut idx = 0.0f32; + while (idx as usize) < items.len() { + result.push(items[idx as usize].clone()); + idx += step; + } + result +} + +// --------------------------------------------------------------------------- +// Racing Line Analysis +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, Serialize, serde::Deserialize)] +pub struct RacingLinePoint { + pub x: f32, + pub y: f32, + pub z: f32, + pub speed_kmh: f32, + pub spline: f32, +} + +#[derive(Debug, Clone, Serialize, serde::Deserialize)] +pub struct RacingLap { + pub label: String, + pub lap_index: usize, + pub point_count: usize, + pub points: Vec, + pub lap_time_ms: i32, + pub length_m: f32, + pub avg_speed_kmh: f32, + pub max_speed_kmh: f32, +} + +#[derive(Debug, Clone, Serialize, serde::Deserialize)] +pub struct RacingLineAnalysis { + pub laps: Vec, + pub position_mode: PositionMode, + pub total_laps: usize, + pub total_frames_analyzed: usize, +} + +/// Split a run's frames into individual laps based on lap_count transitions. +fn split_into_laps(frames: &[TelemetryFrame]) -> Vec> { + if frames.is_empty() { + return Vec::new(); + } + + let mut laps: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + let mut prev_lap = frames[0].lap_count; + + for f in frames { + if f.lap_count != prev_lap && !current.is_empty() { + laps.push(std::mem::take(&mut current)); + } + current.push(f.clone()); + prev_lap = f.lap_count; + } + if !current.is_empty() { + laps.push(current); + } + laps +} + +pub fn analyze_racing_line( + runs: &[Vec], + labels: &[String], +) -> RacingLineAnalysis { + let all_frames: Vec = runs.iter().flat_map(|r| r.iter()).cloned().collect(); + let mode = detect_position_mode(&all_frames); + let mut laps_out: Vec = Vec::new(); + let mut total_frames = 0usize; + + for (run, label) in runs.iter().zip(labels.iter()) { + let laps = split_into_laps(run); + + for (lap_idx, lap_frames) in laps.iter().enumerate() { + if lap_frames.is_empty() { + continue; + } + + // Skip partial laps: check spline coverage. A complete lap's + // spline values span ≥ 0.9 of [0, 1] (the car went almost all + // the way around). Partial laps at the start (joined mid-track) + // and end (session ended early) are discarded. + if laps.len() > 1 { + let splines: Vec = lap_frames.iter() + .filter(|f| f.spline_position > 0.0) + .map(|f| f.spline_position) + .collect(); + if !splines.is_empty() { + let min_s = splines.iter().cloned().fold(f32::INFINITY, f32::min); + let max_s = splines.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let span = max_s - min_s; + let wraps = min_s < 0.1 && max_s > 0.9; + if span < 0.9 && !wraps { + continue; + } + } + } + + let mut points: Vec = lap_frames + .iter() + .filter(|f| { + if matches!(mode, PositionMode::Spline) { + f.spline_position > 0.0 + } else { + f.world_x != 0.0 || f.world_z != 0.0 + } + }) + .map(|f| RacingLinePoint { + x: f.world_x, + y: f.world_y, + z: f.world_z, + speed_kmh: f.speed_kmh, + spline: f.spline_position, + }) + .collect(); + + if points.is_empty() { + continue; + } + + total_frames += lap_frames.len(); + + // Compute track length from consecutive point distances + let mut length_m = 0.0f32; + for i in 1..points.len() { + let dx = points[i].x - points[i - 1].x; + let dz = points[i].z - points[i - 1].z; + length_m += (dx * dx + dz * dz).sqrt(); + } + + // Sort by spline if in spline mode for a clean path + if matches!(mode, PositionMode::Spline) { + points.sort_by(|a, b| { + a.spline + .partial_cmp(&b.spline) + .unwrap_or(std::cmp::Ordering::Equal) + }); + points.dedup_by(|a, b| (a.spline - b.spline).abs() < 0.0001); + } + + // Downsample for efficient rendering (target ~400 points/lap) + let point_count_before = points.len(); + points = downsample(points, 400); + + let max_speed = lap_frames + .iter() + .map(|f| f.speed_kmh) + .fold(0.0f32, f32::max); + + let avg_speed = if length_m > 0.0 { + let best_lap_s = lap_frames + .last() + .map(|f| f.lap_time_ms) + .unwrap_or(0) + .max(0) as f32 + / 1000.0; + if best_lap_s > 0.0 { + (length_m / best_lap_s) * 3.6 + } else { + let frame_count = lap_frames.len() as f32; + lap_frames.iter().map(|f| f.speed_kmh).sum::() / frame_count + } + } else { + 0.0 + }; + + let lap_time = lap_frames + .last() + .map(|f| f.lap_time_ms) + .unwrap_or(0); + + laps_out.push(RacingLap { + label: label.clone(), + lap_index: lap_idx, + point_count: point_count_before, + points, + lap_time_ms: lap_time, + length_m, + avg_speed_kmh: avg_speed, + max_speed_kmh: max_speed, + }); + } + } + + let total_laps = laps_out.len(); + + RacingLineAnalysis { + laps: laps_out, + position_mode: mode, + total_laps, + total_frames_analyzed: total_frames, + } +} + // --------------------------------------------------------------------------- // Dispatch // --------------------------------------------------------------------------- @@ -415,8 +1209,26 @@ pub fn analyze( .unwrap_or_else(|_| serde_json::json!({"error": "serialization failed"})) } } - UseCase::TrackMap => serde_json::to_value(analyze_track_map(frames_by_run, run_labels)) - .unwrap_or_else(|_| serde_json::json!({"error": "serialization failed"})), + UseCase::CarGrip => { + if frames_by_run.is_empty() || frames_by_run.iter().all(|r| r.is_empty()) { + serde_json::json!({"error": "no frames provided"}) + } else { + serde_json::to_value(analyze_car_grip(frames_by_run)) + .unwrap_or_else(|_| serde_json::json!({"error": "serialization failed"})) + } + } + UseCase::TrackMapping => { + serde_json::to_value(analyze_track_map(frames_by_run, run_labels)) + .unwrap_or_else(|_| serde_json::json!({"error": "serialization failed"})) + } + UseCase::RacingLine => { + if frames_by_run.is_empty() || frames_by_run.iter().all(|r| r.is_empty()) { + serde_json::json!({"error": "no frames provided"}) + } else { + serde_json::to_value(analyze_racing_line(frames_by_run, run_labels)) + .unwrap_or_else(|_| serde_json::json!({"error": "serialization failed"})) + } + } _ => serde_json::json!({ "status": "not_implemented", "use_case": format!("{:?}", use_case), diff --git a/src/api.rs b/src/api.rs index 98ca245..500ff91 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! REST API server for recording management and live telemetry access. //! //! Runs as a parallel tokio task alongside the UDP listeners. @@ -14,6 +29,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use tower_http::cors::CorsLayer; use crate::analysis; +use crate::characteristics; use crate::feed_state::FeedState; use crate::recording::{Game, RecordingManager, RecordingStatus, StartRecordingRequest, UseCase}; use crate::session::SessionManager; @@ -24,6 +40,8 @@ pub struct AppState { pub recording_manager: Arc, pub feed_displays: Vec<(FeedDisplayInfo, Arc>)>, pub session_manager: Arc>, + pub track_model_store: Arc, + pub game_info: Arc>>, } #[derive(Serialize)] @@ -89,6 +107,14 @@ struct StartRunRequest { merge_feeds: Vec, } + +#[derive(Deserialize)] +struct BuildTrackRequest { + session_id: String, + game: Option, + track_name: Option, +} + async fn create_session( State(state): State>, Json(req): Json, @@ -96,7 +122,19 @@ async fn create_session( let recording_id = state.recording_manager.active_recording_id().await; let mut mgr = lock_sessions(&state); match mgr.create_session(req.use_case, req.label, recording_id) { - Ok(session) => (StatusCode::CREATED, Json(session)).into_response(), + Ok(session) => { + let (car, track) = state.game_info.lock() + .map(|gi| { + let (c, t) = gi.as_ref().map_or((None, None), |i| { + (i.car_name.clone(), i.track_name.clone()) + }); + (c, t) + }) + .unwrap_or((None, None)); + mgr.fill_session_metadata(&session.id, car, track); + let updated = mgr.get_session(&session.id); + (StatusCode::CREATED, Json(updated.unwrap_or(session))).into_response() + } Err(msg) => err(StatusCode::BAD_REQUEST, &msg), } } @@ -258,7 +296,7 @@ async fn run_analysis( Path(id): Path, ) -> Response { let (use_case, frames_by_run, run_labels, recording_id) = { - let mgr = lock_sessions(&state); + let mut mgr = lock_sessions(&state); match mgr.get_session(&id) { Some(session) => { if session.status != crate::session::SessionStatus::Completed { @@ -309,8 +347,20 @@ async fn get_recording( async fn start_recording( State(state): State>, - Json(req): Json, + Json(mut req): Json, ) -> Response { + // Auto-fill game/track/car from handshake metadata if not specified. + if let Ok(Some(info)) = state.game_info.lock().as_deref() { + if req.game.is_none() { + req.game = Some(Game::AssettoCorsa); + } + if req.track.is_none() { + req.track = info.track_name.clone(); + } + if req.car.is_none() { + req.car = info.car_name.clone(); + } + } match state.recording_manager.start_recording(req).await { Ok(manifest) => (StatusCode::CREATED, Json(manifest)).into_response(), Err(e) => err( @@ -331,6 +381,11 @@ async fn stop_recording(State(state): State>) -> Response { } } +async fn get_game_info(State(state): State>) -> Response { + let info = state.game_info.lock().map(|gi| gi.clone()).unwrap_or(None); + ok_json(info.unwrap_or_default()) +} + async fn stop_specific_recording( State(state): State>, Path(id): Path, @@ -520,6 +575,143 @@ struct UseCaseInfo { guidance: String, } +async fn list_tracks(State(state): State>) -> Response { + match state.track_model_store.list().await { + Ok(summaries) => ok_json(summaries), + Err(e) => err( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("Failed to list tracks: {}", e), + ), + } +} + +async fn get_track( + State(state): State>, + Path((game, track_name)): Path<(String, String)>, +) -> Response { + match state.track_model_store.load(&game, &track_name).await { + Ok(model) => ok_json(model), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + err(StatusCode::NOT_FOUND, "Track model not found") + } + Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => { + err(StatusCode::BAD_REQUEST, &e.to_string()) + } + Err(e) => err( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("Failed to load track model: {}", e), + ), + } +} + +async fn delete_track( + State(state): State>, + Path((game, track_name)): Path<(String, String)>, +) -> Response { + match state.track_model_store.delete(&game, &track_name).await { + Ok(()) => StatusCode::NO_CONTENT.into_response(), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + err(StatusCode::NOT_FOUND, "Track model not found") + } + Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => { + err(StatusCode::BAD_REQUEST, &e.to_string()) + } + Err(e) => err( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("Failed to delete track model: {}", e), + ), + } +} + +async fn get_track_corners( + State(state): State>, + Path((game, track_name)): Path<(String, String)>, +) -> Response { + match state.track_model_store.load(&game, &track_name).await { + Ok(model) => ok_json(&model.corners), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + err(StatusCode::NOT_FOUND, "Track model not found") + } + Err(e) if e.kind() == std::io::ErrorKind::InvalidInput => { + err(StatusCode::BAD_REQUEST, &e.to_string()) + } + Err(e) => err( + StatusCode::INTERNAL_SERVER_ERROR, + &format!("Failed to load track model: {}", e), + ), + } +} + +async fn build_track( + State(state): State>, + Json(req): Json, +) -> Response { + let rec_id = { + let mgr = lock_sessions(&state); + let session = match mgr.get_session(&req.session_id) { + Some(s) => s, + None => return err(StatusCode::NOT_FOUND, "Session not found"), + }; + match session.recording_id.clone() { + Some(id) => id, + None => return err(StatusCode::BAD_REQUEST, "Session has no associated recording"), + } + }; + + let manifest = match state.recording_manager.get_recording(&rec_id).await { + Ok(m) => m, + Err(_) => return err(StatusCode::NOT_FOUND, "Recording not found"), + }; + + let game = req.game.unwrap_or_else(|| manifest.game.to_track_dir_name().to_string()); + let track_name = req.track_name.unwrap_or(manifest.track); + + if game.is_empty() || track_name.is_empty() { + return err(StatusCode::BAD_REQUEST, "Game and track name are required. Specify them in the request or set them when starting the recording."); + } + + let boundaries = { + let mgr = lock_sessions(&state); + let session = match mgr.get_session(&req.session_id) { + Some(s) => s, + None => return err(StatusCode::NOT_FOUND, "Session not found"), + }; + + if session.use_case != UseCase::TrackMapping { + return err(StatusCode::BAD_REQUEST, "Session is not a track_mapping session"); + } + if session.status != crate::session::SessionStatus::Completed { + return err(StatusCode::BAD_REQUEST, "Session must be completed first"); + } + + let analysis = match &session.analysis { + Some(a) => a.clone(), + None => return err(StatusCode::BAD_REQUEST, "Session has no analysis results"), + }; + + let boundaries_val = match analysis.get("boundaries") { + Some(v) => v.clone(), + None => return err(StatusCode::BAD_REQUEST, "No boundaries in analysis"), + }; + + match serde_json::from_value::>(boundaries_val) { + Ok(b) => b, + Err(e) => return err(StatusCode::BAD_REQUEST, &format!("Failed to parse boundaries: {}", e)), + } + }; + + let source = crate::track_model::TrackModelSource::BoundaryRecording; + let track_model = match analysis::build_track_model(&boundaries, game.clone(), track_name.clone(), source) { + Ok(m) => m, + Err(e) => return err(StatusCode::BAD_REQUEST, &format!("Failed to build track model: {}", e)), + }; + + match state.track_model_store.save(&track_model).await { + Ok(()) => (StatusCode::CREATED, Json(track_model)).into_response(), + Err(e) => err(StatusCode::INTERNAL_SERVER_ERROR, &format!("Failed to save track model: {}", e)), + } +} + async fn list_use_cases() -> Response { let use_cases: Vec = UseCase::all() .into_iter() @@ -539,6 +731,24 @@ async fn list_games() -> Response { ok_json(Game::valid_choices()) } +async fn list_car_profiles( + State(state): State>, +) -> Response { + let mgr = lock_sessions(&state); + ok_json(characteristics::car_profiles(&mgr)) +} + +async fn get_car_profile( + State(state): State>, + Path(car): Path, +) -> Response { + let mgr = lock_sessions(&state); + match characteristics::car_profile(&mgr, &car) { + Some(profile) => ok_json(profile), + None => err(StatusCode::NOT_FOUND, &format!("No data for car '{}'", car)), + } +} + pub fn build_router(state: Arc) -> Router { Router::new() .route("/api/sessions", get(list_sessions).post(create_session)) @@ -566,8 +776,15 @@ pub fn build_router(state: Arc) -> Router { get(get_feed_data), ) .route("/api/live", get(get_live)) + .route("/api/game-info", get(get_game_info)) + .route("/api/tracks", get(list_tracks)) + .route("/api/tracks/{game}/{track_name}", get(get_track).delete(delete_track)) + .route("/api/tracks/{game}/{track_name}/corners", get(get_track_corners)) + .route("/api/tracks/build", post(build_track)) .route("/api/use-cases", get(list_use_cases)) .route("/api/games", get(list_games)) + .route("/api/characteristics/cars", get(list_car_profiles)) + .route("/api/characteristics/cars/{car}", get(get_car_profile)) .layer(CorsLayer::permissive()) .with_state(state) } diff --git a/src/binary_utils.rs b/src/binary_utils.rs index ef4cd32..ca3d1bf 100644 --- a/src/binary_utils.rs +++ b/src/binary_utils.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Shared binary reading helpers for UDP packet parsers. //! //! All helpers use `get()` for safe bounds checking — they return a zero/empty @@ -73,11 +88,7 @@ pub fn read_f64(data: &[u8], offset: usize) -> f64 { /// Read an array of 4 little-endian `f32` from the data at the given offset. pub fn read_f32_4(data: &[u8], offset: usize) -> [f32; NUM_WHEELS] { - let mut arr = [0.0f32; NUM_WHEELS]; - for i in 0..NUM_WHEELS { - arr[i] = read_f32(data, offset + i * 4); - } - arr + std::array::from_fn(|i| read_f32(data, offset + i * 4)) } /// Read an array of 2 little-endian `f32` from the data at the given offset. diff --git a/src/characteristics.rs b/src/characteristics.rs new file mode 100644 index 0000000..d4bc089 --- /dev/null +++ b/src/characteristics.rs @@ -0,0 +1,226 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +//! Car & track characteristics database — server-side aggregation across +//! persisted sessions. +//! +//! Aggregates analysis results (currently shift-point data) grouped by car +//! name to build a characteristics profile. This is a read-only query layer +//! over the in-memory session store. + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +use crate::recording::UseCase; +use crate::session::{SessionManager, SessionStatus}; + +/// Aggregated gear range for a single car, merged across all sessions. +#[derive(Debug, Clone, Serialize)] +pub struct CarGearProfile { + pub gear: i32, + pub gear_display: String, + pub min_rpm: f32, + pub max_rpm: f32, + pub min_speed_kmh: f32, + pub max_speed_kmh: f32, + pub session_count: usize, +} + +/// Aggregated shift-point characteristics for a single car. +#[derive(Debug, Clone, Serialize)] +pub struct CarProfile { + pub car_name: String, + pub session_count: usize, + pub recommended_shift_rpm_avg: Option, + pub recommended_shift_rpm_min: Option, + pub recommended_shift_rpm_max: Option, + pub gear_profiles: Vec, + pub last_session_id: String, + pub last_session_date: String, +} + +/// Typed view of a gear curve from serialized `ShiftPointAnalysis`. +/// Mirrors the fields of `analysis::GearAccelerationCurve` so that renaming +/// a field in the serializer produces a compile-time error here. +#[derive(Deserialize)] +struct GearCurveView { + gear: i32, + min_rpm: f64, + max_rpm: f64, + min_speed_kmh: f64, + max_speed_kmh: f64, +} + +/// Typed view of serialized `ShiftPointAnalysis`. +#[derive(Deserialize)] +struct ShiftPointAnalysisView { + recommended_shift_rpm: Option, + gear_curves: Vec, +} + +/// Per-session shift-point data extracted from analysis JSON. +struct SessionShiftData { + car_name: String, + recommended_shift_rpm: Option, + gear_data: HashMap, + session_id: String, + created_at: String, +} + +/// Collect shift-point data from a completed session's analysis JSON. +fn extract_shift_data( + session: &crate::session::UseCaseSession, +) -> Option { + if session.use_case != UseCase::ShiftPoints { + return None; + } + if session.status != SessionStatus::Completed { + return None; + } + let analysis = session.analysis.as_ref()?; + + let view = serde_json::from_value::(analysis.clone()).ok()?; + + let mut gear_data: HashMap = HashMap::new(); + for curve in view.gear_curves { + gear_data.insert( + curve.gear, + ( + curve.min_rpm as f32, + curve.max_rpm as f32, + curve.min_speed_kmh as f32, + curve.max_speed_kmh as f32, + ), + ); + } + + let car_name = session + .car_name + .clone() + .unwrap_or_else(|| "Unknown".to_string()); + + Some(SessionShiftData { + car_name, + recommended_shift_rpm: view.recommended_shift_rpm.map(|f| f as f32), + gear_data, + session_id: session.id.clone(), + created_at: session.created_at.clone(), + }) +} + +fn gear_display(gear: i32) -> String { + crate::telemetry_frame::gear_display(gear) +} + +/// Aggregate all shift-point sessions into per-car profiles. +pub fn car_profiles(mgr: &SessionManager) -> Vec { + let sessions: Vec = mgr + .iter_sessions() + .filter_map(extract_shift_data) + .collect(); + + let mut by_car: HashMap> = HashMap::new(); + for data in sessions { + by_car.entry(data.car_name.clone()).or_default().push(data); + } + + let mut profiles: Vec = by_car + .into_iter() + .map(|(car_name, sessions)| build_profile(&car_name, &sessions)) + .collect(); + + profiles.sort_by(|a, b| a.car_name.cmp(&b.car_name)); + profiles +} + +/// Aggregate a single car profile by name. +pub fn car_profile(mgr: &SessionManager, car: &str) -> Option { + let sessions: Vec = mgr + .iter_sessions() + .filter_map(extract_shift_data) + .filter(|d| d.car_name.eq_ignore_ascii_case(car)) + .collect(); + + if sessions.is_empty() { + return None; + } + + Some(build_profile(car, &sessions)) +} + +fn build_profile(car_name: &str, sessions: &[SessionShiftData]) -> CarProfile { + let session_count = sessions.len(); + + // Recommended shift RPM aggregation. + let shift_rpms: Vec = sessions + .iter() + .filter_map(|d| d.recommended_shift_rpm) + .collect(); + + let (recommended_avg, recommended_min, recommended_max) = if shift_rpms.is_empty() { + (None, None, None) + } else { + let sum: f32 = shift_rpms.iter().sum(); + let avg = sum / shift_rpms.len() as f32; + let min = shift_rpms.iter().cloned().fold(f32::INFINITY, f32::min); + let max = shift_rpms.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + (Some(avg), Some(min), Some(max)) + }; + + // Gear profile aggregation: merge min/max across sessions per gear. + let mut gear_agg: HashMap = HashMap::new(); + for session in sessions { + for (&gear, &(min_rpm, max_rpm, min_spd, max_spd)) in &session.gear_data { + let entry = gear_agg + .entry(gear) + .or_insert((f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, f32::NEG_INFINITY, 0)); + entry.0 = entry.0.min(min_rpm); + entry.1 = entry.1.max(max_rpm); + entry.2 = entry.2.min(min_spd); + entry.3 = entry.3.max(max_spd); + entry.4 += 1; + } + } + + let mut gear_profiles: Vec = gear_agg + .into_iter() + .map(|(gear, (min_rpm, max_rpm, min_spd, max_spd, count))| CarGearProfile { + gear, + gear_display: gear_display(gear), + min_rpm, + max_rpm, + min_speed_kmh: min_spd, + max_speed_kmh: max_spd, + session_count: count, + }) + .collect(); + gear_profiles.sort_by_key(|g| g.gear); + + let last = sessions + .iter() + .max_by(|a, b| a.created_at.cmp(&b.created_at)) + .expect("at least one session"); + + CarProfile { + car_name: car_name.to_string(), + session_count, + recommended_shift_rpm_avg: recommended_avg, + recommended_shift_rpm_min: recommended_min, + recommended_shift_rpm_max: recommended_max, + gear_profiles, + last_session_id: last.session_id.clone(), + last_session_date: last.created_at.clone(), + } +} diff --git a/src/feed_state.rs b/src/feed_state.rs index db10dda..3926f62 100644 --- a/src/feed_state.rs +++ b/src/feed_state.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . use crate::telemetry_frame::TelemetryFrame; use std::time::Instant; diff --git a/src/main.rs b/src/main.rs index a9fad8b..31da406 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . mod api; mod binary_utils; mod feed_state; @@ -5,12 +20,15 @@ mod parser_ksudp; mod parser_pcars; mod parser_telemetry_tool; mod recording; +mod track_model; mod telemetry_frame; mod ui; mod warnings; mod analysis; +mod characteristics; mod session; +use serde::Serialize; use feed_state::*; use ui::*; @@ -36,13 +54,50 @@ use crate::warnings::Warnings; const VERSION: &str = env!("CARGO_PKG_VERSION"); const BUFFER_SIZE: usize = 65535; const RENDER_INTERVAL_MS: u64 = 250; -const HANDSHAKE_INTERVAL_SECS: u64 = 10; +const HANDSHAKE_INTERVAL_SECS: u64 = 5; const HANDSHAKE_RESPONSE_SIZE: usize = 408; +const STALE_TIMEOUT_SECS: u64 = 5; const HANDSHAKE_REQUEST: [u8; 12] = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]; const SUBSCRIBE_UPDATE: [u8; 12] = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]; const API_PORT: u16 = 8080; +/// Metadata extracted from the KSUDP handshake response. +/// Updated whenever AC reconnects (track/car change) and shared +/// with the API for auto-filling recording and session metadata. +#[derive(Debug, Clone, Serialize, Default)] +pub struct GameInfo { + #[serde(skip_serializing_if = "Option::is_none")] + pub car_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub track_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub driver_name: Option, +} + +/// Parse a 408-byte KSUDP HandshakerResponse into GameInfo. +/// Layout: car_name (0-100), driver_name (100-200), identifier (200-204), +/// version (204-208), track_name (208-308), track_config (308-408). +fn parse_handshake_response(data: &[u8]) -> Option { + if data.len() < HANDSHAKE_RESPONSE_SIZE { + return None; + } + let car_name = decode_utf16le(&data[0..100]); + let driver_name = decode_utf16le(&data[100..200]); + let track_name = decode_utf16le(&data[208..308]); + + let clean = |s: String| -> Option { + let trimmed = s.trim_end_matches('\0').trim().to_string(); + if trimmed.is_empty() { None } else { Some(trimmed) } + }; + + Some(GameInfo { + car_name: clean(car_name), + driver_name: clean(driver_name), + track_name: clean(track_name), + }) +} + fn api_port() -> u16 { std::env::var("RUSTY_TELEMETRY_API_PORT") .ok() @@ -166,6 +221,7 @@ async fn run_feed( state: Arc>, warnings: Warnings, mut shutdown_rx: tokio::sync::watch::Receiver, + game_info: Arc>>, ) { let handshake_target: Option = if feed.needs_handshake { let target: std::net::SocketAddr = match format!("{}:{}", game_host(), feed.port).parse() { @@ -204,34 +260,25 @@ async fn run_feed( .await { Ok(Ok((len, _src))) if len == HANDSHAKE_RESPONSE_SIZE => { - let car_name = decode_utf16le(&hs_buf[0..100]); - let driver_name = decode_utf16le(&hs_buf[100..200]); - let identifier = i32::from_le_bytes([ - hs_buf[200], hs_buf[201], hs_buf[202], hs_buf[203], - ]); - let version = i32::from_le_bytes([ - hs_buf[204], hs_buf[205], hs_buf[206], hs_buf[207], - ]); - let track_name = decode_utf16le(&hs_buf[208..308]); - let track_config = decode_utf16le(&hs_buf[308..408]); - - warnings.info(&format!( - "{} :{} Phase 2: HandshakerResponse received", - feed.label, feed.port - )); - warnings.info(&format!( - " car_name=\"{}\" driver_name=\"{}\" id={} ver={}", - car_name, driver_name, identifier, version - )); - warnings.info(&format!( - " track_name=\"{}\" track_config=\"{}\"", - track_name, track_config - )); - - if identifier != 4242 { + let info = parse_handshake_response(&hs_buf[..len]); + if let Some(ref info) = info { + warnings.info(&format!( + "{} :{} Phase 2: HandshakerResponse received", + feed.label, feed.port + )); + warnings.info(&format!( + " car=\"{}\" driver=\"{}\" track=\"{}\"", + info.car_name.as_deref().unwrap_or("?"), + info.driver_name.as_deref().unwrap_or("?"), + info.track_name.as_deref().unwrap_or("?"), + )); + if let Ok(mut gi) = game_info.lock() { + *gi = Some(info.clone()); + } + } else { warnings.warn(&format!( - "{} :{} Unexpected handshake identifier: {} (expected 4242)", - feed.label, feed.port, identifier + "{} :{} Phase 2: Failed to parse handshake response", + feed.label, feed.port )); } } @@ -283,9 +330,13 @@ async fn run_feed( let mut buf = vec![0u8; BUFFER_SIZE]; let mut string_cache = CachedStrings::new(); + let mut last_recv_time: Option = None; + let stale_timeout = Duration::from_secs(STALE_TIMEOUT_SECS); let mut hs_interval: Option = handshake_target.map(|_| { - tokio::time::interval(Duration::from_secs(HANDSHAKE_INTERVAL_SECS)) + let mut iv = tokio::time::interval(Duration::from_secs(HANDSHAKE_INTERVAL_SECS)); + iv.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + iv }); loop { @@ -293,12 +344,32 @@ async fn run_feed( result = socket.recv_from(&mut buf) => { match result { Ok((len, _src)) => { - let parsed: Option = if feed.needs_handshake { - if len != HANDSHAKE_RESPONSE_SIZE { - parser_ksudp::parse_rt_car_info(&buf[..len]).ok() - } else { - None + // Handle handshake response packets (AC reconnected with new track/car). + if feed.needs_handshake && len == HANDSHAKE_RESPONSE_SIZE { + if let Some(info) = parse_handshake_response(&buf[..len]) { + warnings.info(&format!( + "{} :{} Re-handshake: car=\"{}\" track=\"{}\"", + feed.label, feed.port, + info.car_name.as_deref().unwrap_or("?"), + info.track_name.as_deref().unwrap_or("?"), + )); + if let Ok(mut gi) = game_info.lock() { + *gi = Some(info); + } + if let Some(target) = handshake_target { + let _ = socket.send_to(&SUBSCRIBE_UPDATE, target).await; + } + if let Ok(mut s) = state.lock() { + s.set_handshake_phase(HandshakePhase::Subscribed); + } } + continue; + } + + last_recv_time = Some(std::time::Instant::now()); + + let parsed: Option = if feed.needs_handshake { + parser_ksudp::parse_rt_car_info(&buf[..len]).ok() } else if feed.name == "pcars" { match parser_pcars::parse_pcars_packet(&buf[..len]) { Ok(parser_pcars::PcarsPacket::V1Telemetry(f)) => Some(f), @@ -352,11 +423,24 @@ async fn run_feed( } } => { if let Some(target) = handshake_target { - if let Err(e) = socket.send_to(&SUBSCRIBE_UPDATE, target).await { - warnings.warn(&format!( - "Periodic SUBSCRIBE_UPDATE send failed for :{}: {}", - feed.port, e - )); + let is_stale = last_recv_time.is_none_or(|t| t.elapsed() > stale_timeout); + if is_stale { + if let Ok(mut s) = state.lock() { + s.set_handshake_phase(HandshakePhase::WaitingForResponse); + } + if let Err(e) = socket.send_to(&HANDSHAKE_REQUEST, target).await { + warnings.warn(&format!( + "HANDSHAKE_REQUEST send failed for :{}: {}", + feed.port, e + )); + } + } else { + if let Err(e) = socket.send_to(&SUBSCRIBE_UPDATE, target).await { + warnings.warn(&format!( + "SUBSCRIBE_UPDATE send failed for :{}: {}", + feed.port, e + )); + } } } } @@ -386,10 +470,18 @@ async fn main() { } let recording_manager = Arc::new(recording::RecordingManager::new(&data_dir)); + let track_model_store = Arc::new(crate::track_model::TrackModelStore::new(&data_dir)); let session_manager = Arc::new(std::sync::Mutex::new( - SessionManager::new(recording_manager.clone()) + SessionManager::new(recording_manager.clone(), data_dir.clone()) )); + { + let mut mgr = session_manager.lock().unwrap(); + mgr.load_all(); + let count = mgr.list_sessions().len(); + warnings.info(&format!("Loaded {} persisted session(s) from disk", count)); + } + let auto_start = recording::StartRecordingRequest { name: Some( chrono::Local::now() @@ -427,6 +519,9 @@ async fn main() { let mut feed_tasks: Vec> = Vec::new(); let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false); + let game_info: Arc>> = + Arc::new(std::sync::Mutex::new(None)); + for feed in FEEDS { let state = Arc::new(std::sync::Mutex::new(FeedState::new())); @@ -482,8 +577,9 @@ async fn main() { let rm = recording_manager.clone(); let w = warnings.clone(); let sh = shutdown_rx.clone(); + let gi = game_info.clone(); feed_tasks.push(tokio::spawn(async move { - run_feed(feed_clone, socket, rm, state, w, sh).await; + run_feed(feed_clone, socket, rm, state, w, sh, gi).await; })); } } @@ -492,6 +588,8 @@ async fn main() { recording_manager: recording_manager.clone(), feed_displays: feed_displays.clone(), session_manager: session_manager.clone(), + track_model_store, + game_info: game_info.clone(), }); let api_addr = api_bind_addr(); warnings.info(&format!("REST API server will listen on {}", api_addr)); diff --git a/src/parser_ksudp.rs b/src/parser_ksudp.rs index 64d1380..3e1ffba 100644 --- a/src/parser_ksudp.rs +++ b/src/parser_ksudp.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Binary parser for KSUDP RTCarInfo packets (Assetto Corsa port 9996). //! //! After the 3-phase handshake, AC sends continuous RTCarInfo structs at ~20 Hz. @@ -5,8 +20,10 @@ //! //! IMPORTANT: The AC RTCarInfo C struct uses **natural alignment** (not packed). //! This means padding bytes exist: -//! - 3 bytes after `char identifier` (offset 0) before `int size` (offset 4) -//! - 2 bytes after the 6 bools (offsets 20–25) before the next float (offset 28) +//! +//! - 3 bytes after `char identifier` (offset 0) before `int size` (offset 4) +//! - 2 bytes after the 6 bools (offsets 20-25) before the next float (offset 28) +//! //! Total struct size: 328 bytes (not 323). use crate::binary_utils::{read_bool, read_f32, read_f32_4, read_i32}; diff --git a/src/parser_pcars.rs b/src/parser_pcars.rs index f0bacc8..5b98af3 100644 --- a/src/parser_pcars.rs +++ b/src/parser_pcars.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Binary parser for Project CARS 1 & 2 UDP telemetry packets (port 5606). //! //! Both PCARS1 and PCARS2 broadcast on port 5606. The parser auto-detects the @@ -60,20 +75,12 @@ fn read_i8_at(data: &[u8], offset: usize) -> i8 { /// Read 4 consecutive u8 values starting at offset. fn read_u8_4(data: &[u8], offset: usize) -> [u8; NUM_WHEELS] { - let mut arr = [0u8; NUM_WHEELS]; - for i in 0..NUM_WHEELS { - arr[i] = read_u8_at(data, offset + i); - } - arr + std::array::from_fn(|i| read_u8_at(data, offset + i)) } /// Read 4 consecutive i16 values starting at offset. fn read_i16_4(data: &[u8], offset: usize) -> [i16; NUM_WHEELS] { - let mut arr = [0i16; NUM_WHEELS]; - for i in 0..NUM_WHEELS { - arr[i] = read_i16(data, offset + i * 2); - } - arr + std::array::from_fn(|i| read_i16(data, offset + i * 2)) } /// Normalize u8 (0–255) to f32 (0.0–1.0). @@ -166,6 +173,21 @@ fn parse_v1_telemetry(data: &[u8]) -> Result { // Track length let track_length = read_f32(data, 1360); + // V1 position data from viewed participant + let viewed_idx = read_i8_at(data, 4) as usize; + let participant_offset = 464 + viewed_idx * 16; + let v1_world_x = read_i16(data, participant_offset) as f32; + let v1_world_y = read_i16(data, participant_offset + 2) as f32; + let v1_world_z = read_i16(data, participant_offset + 4) as f32; + let current_lap_distance = read_u16(data, participant_offset + 6); + let spline_pos = if track_length > 0.0 { + (current_lap_distance as f32 / track_length).clamp(0.0, 1.0) + } else { + 0.0 + }; + let laps_completed = (read_u8_at(data, participant_offset + 9) & 0x7F) as i32; + let _current_lap = read_u8_at(data, participant_offset + 10) as i32; + let frame = TelemetryFrame { source: FeedSource::Pcars, raw_size: data.len(), @@ -185,12 +207,12 @@ fn parse_v1_telemetry(data: &[u8]) -> Result { lap_time_ms: (current_lap_s * 1000.0) as i32, last_lap_ms: (last_lap_s * 1000.0) as i32, best_lap_ms: (best_lap_s * 1000.0) as i32, - lap_count: 0, // Not directly in V1 telemetry packet + lap_count: laps_completed, - world_x: 0.0, - world_y: 0.0, - world_z: 0.0, - spline_position: 0.0, + world_x: v1_world_x, + world_y: v1_world_y, + world_z: v1_world_z, + spline_position: spline_pos, acc_g_vertical: acc_vert, acc_g_horizontal: acc_horiz, @@ -237,7 +259,8 @@ fn parse_v1_telemetry(data: &[u8]) -> Result { track_temperature: Some(track_temp), rain_density: Some(rain_density), track_length: Some(track_length), - full_position: None, // V1 does not have full 3D position + full_position: Some([v1_world_x, v1_world_y, v1_world_z]), + current_lap_distance: Some(current_lap_distance), tyre_wear: Some(read_u8_4(data, 316)), brake_temp_celsius: Some(read_i16_4(data, 328)), suspension_damage: Some(read_u8_4(data, 324)), @@ -359,6 +382,7 @@ fn parse_v2_car_physics(data: &[u8]) -> Result tyre_wear: Some(read_u8_4(data, 196)), brake_temp_celsius: Some(read_i16_4(data, 208)), suspension_damage: Some(read_u8_4(data, 204)), + current_lap_distance: None, ..Default::default() }; @@ -394,6 +418,15 @@ mod tests { // Current time at 20 = 42.5 seconds packet[20..24].copy_from_slice(&42.5f32.to_le_bytes()); + // World position for participant 0 at offset 464: x=100, y=5, z=-200 + packet[464..466].copy_from_slice(&100i16.to_le_bytes()); + packet[466..468].copy_from_slice(&5i16.to_le_bytes()); + packet[468..470].copy_from_slice(&(-200i16).to_le_bytes()); + // Current lap distance at offset 464+6 = 470: 2500 meters + packet[470..472].copy_from_slice(&2500u16.to_le_bytes()); + // Track length at offset 1360: 5000.0 meters + packet[1360..1364].copy_from_slice(&5000.0f32.to_le_bytes()); + let result = parse_pcars_packet(&packet).unwrap(); match result { PcarsPacket::V1Telemetry(frame) => { @@ -407,7 +440,13 @@ mod tests { assert_eq!(frame.best_lap_ms, 78123); assert_eq!(frame.last_lap_ms, 80456); assert_eq!(frame.lap_time_ms, 42500); - assert_eq!(frame.oil_temp_celsius, Some(0)); // default + assert!((frame.world_x - 100.0).abs() < 0.1); + assert!((frame.world_y - 5.0).abs() < 0.1); + assert!((frame.world_z - (-200.0)).abs() < 0.1); + assert!((frame.spline_position - 0.5).abs() < 0.01); + assert!(frame.full_position.is_some()); + assert_eq!(frame.current_lap_distance, Some(2500)); + assert_eq!(frame.oil_temp_celsius, Some(0)); assert!(frame.aero_damage.is_some()); } _ => panic!("Expected V1Telemetry"), @@ -492,4 +531,35 @@ mod tests { let result = parse_pcars_packet(&packet); assert!(matches!(result, Ok(PcarsPacket::V2Other))); } + + #[test] + fn test_v1_position_nonzero_viewed_participant() { + let mut packet = vec![0u8; V1_TELEMETRY_SIZE]; + packet[0..2].copy_from_slice(&1104u16.to_le_bytes()); + packet[2] = 0x00; + + packet[4] = 3i8.to_le_bytes()[0]; + + packet[120..124].copy_from_slice(&30.0f32.to_le_bytes()); + + packet[1360..1364].copy_from_slice(&6000.0f32.to_le_bytes()); + + let p_offset = 464 + 3 * 16; + packet[p_offset..p_offset+2].copy_from_slice(&300i16.to_le_bytes()); + packet[p_offset+2..p_offset+4].copy_from_slice(&10i16.to_le_bytes()); + packet[p_offset+4..p_offset+6].copy_from_slice(&(-400i16).to_le_bytes()); + packet[p_offset+6..p_offset+8].copy_from_slice(&3000u16.to_le_bytes()); + + let result = parse_pcars_packet(&packet).unwrap(); + match result { + PcarsPacket::V1Telemetry(frame) => { + assert!((frame.world_x - 300.0).abs() < 0.1); + assert!((frame.world_y - 10.0).abs() < 0.1); + assert!((frame.world_z - (-400.0)).abs() < 0.1); + assert!((frame.spline_position - 0.5).abs() < 0.01); + assert_eq!(frame.current_lap_distance, Some(3000)); + } + _ => panic!("Expected V1Telemetry"), + } + } } diff --git a/src/parser_telemetry_tool.rs b/src/parser_telemetry_tool.rs index 8a22c2b..43aeda0 100644 --- a/src/parser_telemetry_tool.rs +++ b/src/parser_telemetry_tool.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Binary parser for Telemetry Tool plugin packets (port 10101). //! //! The Telemetry Tool is a third-party AC Python plugin by IkoRein v1.3. diff --git a/src/recording.rs b/src/recording.rs index d0fa718..7ba4404 100644 --- a/src/recording.rs +++ b/src/recording.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Recording session management with always-on ring buffers. //! //! Each feed has a rolling ring buffer holding the last 5 minutes of telemetry frames. @@ -78,6 +93,7 @@ impl RingBuffer { } /// Number of frames currently stored. + #[allow(dead_code)] pub fn len(&self) -> usize { self.frames.len() } @@ -88,11 +104,13 @@ impl RingBuffer { } /// Total frames ever pushed (monotonically increasing). + #[allow(dead_code)] pub fn total_pushed(&self) -> u64 { self.total_pushed } /// Number of frames evicted due to ring overflow. + #[allow(dead_code)] pub fn dropped_count(&self) -> u64 { self.dropped_count } @@ -128,11 +146,12 @@ impl RingBuffer { #[serde(rename_all = "snake_case")] pub enum UseCase { ShiftPoints, + CarGrip, RacingLine, BrakingAnalysis, LapTimes, SectorAnalysis, - TrackMap, + TrackMapping, General, } @@ -140,23 +159,25 @@ impl UseCase { pub fn all() -> Vec { vec![ UseCase::ShiftPoints, + UseCase::CarGrip, UseCase::RacingLine, UseCase::BrakingAnalysis, UseCase::LapTimes, UseCase::SectorAnalysis, - UseCase::TrackMap, + UseCase::TrackMapping, UseCase::General, ] } pub fn guidance(&self) -> &'static str { match self { UseCase::ShiftPoints => "Record one run per gear: accelerate at full throttle from as low an RPM as possible to the rev limiter (or until you run out of road). Each run should be in a single gear only. Use Hotlap mode on a long straight. Start recording a run just before going WOT, stop after reaching max RPM. Repeat for each gear.", - UseCase::TrackMap => "Record two runs on the same lap: one driving the left boundary, one driving the right boundary. Label each run accordingly.", + UseCase::CarGrip => "Drive 3–5 laps at race pace. Brake hard, carry speed through corners, and accelerate aggressively out of slow corners. The harder you push, the more complete the grip profile. Different corner types (hairpins, sweepers, high-speed) help fill the curve across the speed range.", UseCase::BrakingAnalysis => "Record runs with heavy braking into corners from high speed.", UseCase::LapTimes => "Record one or more complete laps.", UseCase::SectorAnalysis => "Record one or more complete laps.", UseCase::RacingLine => "Record multiple laps with different racing line approaches.", UseCase::General => "Record freely - no specific procedure required.", + UseCase::TrackMapping => "Step-by-step boundary recording for track model creation.\n\nStep 1: Start Run 1 — Drive a slow, clean lap hugging the LEFT edge of the track. Label this run 'left'.\nStep 2: Start Run 2 — Drive a slow, clean lap hugging the RIGHT edge of the track. Label this run 'right'.\n\nAfter both runs, complete the session. The system will automatically build a TrackModel from your boundary data.", } } } @@ -181,6 +202,16 @@ impl Game { Game::ProjectCars2, ] } + /// Returns a filesystem-safe string identifier for the game. + pub fn to_track_dir_name(&self) -> &'static str { + match self { + Game::AssettoCorsa => "assetto_corsa", + Game::AssettoCorsaCompetizione => "assetto_corsa_competizione", + Game::ProjectCars1 => "project_cars_1", + Game::ProjectCars2 => "project_cars_2", + Game::Unknown => "unknown", + } + } } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -308,6 +339,7 @@ impl RecordingManager { } /// Get ring buffer stats for a feed. + #[allow(dead_code)] pub fn ring_stats(&self, feed_name: &str) -> Option<(usize, u64, u64)> { self.ring_buffers.get(feed_name) .and_then(|b| b.lock().ok()) @@ -424,8 +456,7 @@ impl RecordingManager { } if !flush_errors.is_empty() { - return Err(std::io::Error::new( - std::io::ErrorKind::Other, + return Err(std::io::Error::other( format!("Flush errors: {}", flush_errors.join(", ")), )); } diff --git a/src/session.rs b/src/session.rs index 7bf6e87..f4998ec 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1,12 +1,33 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Use-case driven session management for telemetry analysis. //! //! Users create sessions tied to specific analysis goals (shift point analysis, //! track mapping, braking analysis, etc.). Each session contains multiple "runs" //! that capture telemetry frames from the always-on ring buffer between start/stop //! markers. Frames are stored in-memory and can be retrieved for analysis. +//! +//! Persistence: session metadata is written to `data/sessions/.json` +//! (compact, without frames). Frame data is written separately to +//! `data/sessions/.frames.json` off-thread. On startup, only metadata is +//! loaded; frames are lazy-loaded on demand via [`SessionManager::ensure_frames_loaded`]. use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::recording::{RecordingManager, UseCase}; @@ -78,6 +99,10 @@ pub struct UseCaseSession { #[serde(default)] pub guidance: String, pub recording_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub car_name: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub track_name: Option, } impl UseCaseSession { @@ -93,23 +118,205 @@ impl UseCaseSession { analysis: self.analysis.clone(), guidance: self.guidance.clone(), recording_id: self.recording_id.clone(), + car_name: self.car_name.clone(), + track_name: self.track_name.clone(), } } } +/// Serialized form of run frames for the `.frames.json` file. +/// One entry per run, in the same order as `UseCaseSession.runs`. +#[derive(Serialize, Deserialize)] +struct SessionFramesFile { + runs: Vec>, +} + pub struct SessionManager { sessions: HashMap, recording_manager: Arc, + data_dir: PathBuf, } impl SessionManager { - pub fn new(recording_manager: Arc) -> Self { + pub fn new( + recording_manager: Arc, + data_dir: PathBuf, + ) -> Self { + let sessions_dir = data_dir.join("sessions"); + let _ = std::fs::create_dir_all(&sessions_dir); Self { sessions: HashMap::new(), recording_manager, + data_dir, } } + fn sessions_dir(&self) -> PathBuf { + self.data_dir.join("sessions") + } + + fn session_file_path(&self, id: &str) -> PathBuf { + self.sessions_dir().join(format!("{}.json", id)) + } + + fn frames_file_path(&self, id: &str) -> PathBuf { + self.sessions_dir().join(format!("{}.frames.json", id)) + } + + /// Atomically write bytes to a path via temp file + rename (same directory). + /// Uses a unique temp file name to avoid collisions between concurrent writes. + fn atomic_write(path: &Path, bytes: &[u8]) { + let tmp = path.with_file_name(format!( + ".{}.{}.tmp", + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), + uuid::Uuid::new_v4() + )); + if let Err(e) = std::fs::write(&tmp, bytes) { + eprintln!("[WARN] Failed to write temp file {}: {}", tmp.display(), e); + return; + } + if let Err(e) = std::fs::rename(&tmp, path) { + eprintln!("[WARN] Failed to rename temp file {}: {}", tmp.display(), e); + let _ = std::fs::remove_file(&tmp); + } + } + + /// Persist session metadata (compact JSON, excludes frames) and frame data + /// synchronously. Both files use atomic write (temp file + rename). + fn persist_session(&self, id: &str) { + let Some(session) = self.sessions.get(id) else { + return; + }; + let id = id.to_string(); + + // Metadata is small (no frames) — write synchronously with atomic rename. + let meta_path = self.session_file_path(&id); + match serde_json::to_vec(session) { + Ok(bytes) => Self::atomic_write(&meta_path, &bytes), + Err(e) => eprintln!("[WARN] Failed to serialize session metadata {}: {}", id, e), + } + + // Frames — clone under lock, then serialize + write synchronously. + // Must be synchronous: off-thread writes race on the same file, + // and an earlier call (with empty frames) can overwrite a later one. + let runs_frames: Vec> = + session.runs.iter().map(|r| r.frames.clone()).collect(); + let frames_path = self.frames_file_path(&id); + let frames_file = SessionFramesFile { runs: runs_frames }; + match serde_json::to_vec(&frames_file) { + Ok(bytes) => Self::atomic_write(&frames_path, &bytes), + Err(e) => eprintln!("[WARN] Failed to serialize frames for session {}: {}", id, e), + } + } + + fn delete_session_file(&self, id: &str) { + for path in [self.session_file_path(id), self.frames_file_path(id)] { + if path.exists() { + if let Err(e) = std::fs::remove_file(&path) { + eprintln!("[WARN] Failed to delete file {}: {}", path.display(), e); + } + } + } + } + + /// Load all persisted session metadata from disk into memory. + /// + /// Only metadata files (`.json`) are loaded — not frame data + /// (`.frames.json`), which is lazy-loaded on demand. Any run found + /// in the `Recording` state (left over from an interrupted session) is + /// normalized to `Stopped` with `data_truncated = true`, since the ring + /// buffer it referenced no longer exists. + pub fn load_all(&mut self) { + let entries = match std::fs::read_dir(self.sessions_dir()) { + Ok(e) => e, + Err(_) => return, + }; + for entry in entries.flatten() { + let path = entry.path(); + let name = match path.file_name().and_then(|n| n.to_str()) { + Some(n) => n, + None => continue, + }; + // Skip frame files — loaded lazily. + if name.ends_with(".frames.json") { + continue; + } + if path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + match std::fs::read_to_string(&path) { + Ok(json) => match serde_json::from_str::(&json) { + Ok(mut session) => { + for run in &mut session.runs { + if run.status == RunStatus::Recording { + run.status = RunStatus::Stopped; + run.data_truncated = true; + } + } + self.sessions.insert(session.id.clone(), session); + } + Err(e) => { + eprintln!( + "[WARN] Failed to parse session file {}: {}", + path.display(), + e + ); + } + }, + Err(e) => { + eprintln!( + "[WARN] Failed to read session file {}: {}", + path.display(), + e + ); + } + } + } + } + + /// Lazy-load frame data for a session from its `.frames.json` file. + /// Called before operations that need frames (analysis, etc.). + /// No-op if frames are already populated or the file doesn't exist. + pub fn ensure_frames_loaded(&mut self, id: &str) { + let needs_load = self + .sessions + .get(id) + .map(|s| s.runs.iter().any(|r| r.frame_count > 0 && r.frames.is_empty())) + .unwrap_or(false); + if !needs_load { + return; + } + + let frames_path = self.frames_file_path(id); + let frames_file = match std::fs::read(&frames_path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + { + Some(f) => f, + None => { + eprintln!( + "[WARN] Failed to load frames for session {} from {}", + id, + frames_path.display() + ); + return; + } + }; + + if let Some(session) = self.sessions.get_mut(id) { + for (run, frames) in session.runs.iter_mut().zip(frames_file.runs) { + if run.frames.is_empty() { + run.frames = frames; + } + } + } + } + + /// Read-only iterator over all sessions (for characteristics aggregation). + pub fn iter_sessions(&self) -> impl Iterator { + self.sessions.values() + } + pub fn create_session( &mut self, use_case: UseCase, @@ -130,11 +337,26 @@ impl SessionManager { analysis: None, guidance, recording_id, + car_name: None, + track_name: None, }; - self.sessions.insert(id, session.clone()); + self.sessions.insert(id.clone(), session.clone()); + self.persist_session(&id); Ok(session) } + /// Update car_name and track_name on a session if they are not yet set. + pub fn fill_session_metadata(&mut self, id: &str, car: Option, track: Option) { + if let Some(session) = self.sessions.get_mut(id) { + if session.car_name.is_none() { + session.car_name = car.filter(|c| !c.is_empty()); + } + if session.track_name.is_none() { + session.track_name = track.filter(|t| !t.is_empty()); + } + } + } + pub fn list_sessions(&mut self) -> Vec { let mut sessions: Vec = self .sessions @@ -188,6 +410,7 @@ impl SessionManager { }; let summary = run.summary_clone(); session.runs.push(run); + self.persist_session(session_id); Ok(summary) } @@ -213,7 +436,14 @@ impl SessionManager { Self::finalize_run(&self.recording_manager, run); - Ok(run.summary_clone()) + let summary = run.summary_clone(); + let car_name = extract_car_name(&session.runs); + if session.car_name.is_none() { + session.car_name = car_name; + } + + self.persist_session(session_id); + Ok(summary) } fn finalize_run(recording_manager: &Arc, run: &mut SessionRun) { @@ -267,10 +497,18 @@ impl SessionManager { } } + // Cache car name from finalized frames. + let car_name = extract_car_name(&session.runs); + if session.car_name.is_none() { + session.car_name = car_name; + } + session.status = SessionStatus::Completed; session.completed_at = Some(chrono::Utc::now().to_rfc3339()); - Ok(session.summary_clone()) + let summary = session.summary_clone(); + self.persist_session(id); + Ok(summary) } pub fn delete_run(&mut self, session_id: &str, run_id: &str) -> Result<(), String> { @@ -295,6 +533,7 @@ impl SessionManager { session.analysis = None; } + self.persist_session(session_id); Ok(()) } @@ -312,7 +551,9 @@ impl SessionManager { session.completed_at = None; session.analysis = None; - Ok(session.summary_clone()) + let summary = session.summary_clone(); + self.persist_session(session_id); + Ok(summary) } pub fn set_analysis( @@ -325,15 +566,20 @@ impl SessionManager { .get_mut(session_id) .ok_or_else(|| format!("Session '{}' not found", session_id))?; session.analysis = Some(result); + self.persist_session(session_id); Ok(()) } /// Collect frames and labels from all runs for analysis. /// - /// Clones frames to allow the caller to release the SessionManager lock - /// before running CPU-bound analysis. Frames must remain in runs for - /// potential re-analysis via `POST /api/sessions/{id}/analyze`. - pub fn collect_run_frames(&self, session_id: &str) -> Option<(UseCase, Vec>, Vec)> { + /// Lazy-loads frame data from disk if needed, then clones frames to allow + /// the caller to release the SessionManager lock before running CPU-bound + /// analysis. Frames must remain in runs for potential re-analysis. + pub fn collect_run_frames( + &mut self, + session_id: &str, + ) -> Option<(UseCase, Vec>, Vec)> { + self.ensure_frames_loaded(session_id); let session = self.sessions.get(session_id)?; let mut frames_by_run = Vec::new(); let mut run_labels = Vec::new(); @@ -348,10 +594,25 @@ impl SessionManager { self.sessions .remove(id) .ok_or_else(|| format!("Session '{}' not found", id))?; + self.delete_session_file(id); Ok(()) } } +/// Extract the car name from the first frame (across all runs) that has one. +fn extract_car_name(runs: &[SessionRun]) -> Option { + for run in runs { + for frame in &run.frames { + if let Some(ref name) = frame.car_name { + if !name.is_empty() { + return Some(name.clone()); + } + } + } + } + None +} + /// Merge frames from multiple feeds into a single sorted, deduplicated sequence. /// /// Frames are sorted by `(lap_count, lap_time_ms)`. Near-duplicate frames @@ -377,7 +638,7 @@ fn merge_frames(mut frames: Vec) -> Vec { { // Near-duplicate: keep higher-priority frame at write position if feed_priority(frames[read].source) > feed_priority(frames[write].source) { - frames[write] = std::mem::replace(&mut frames[read], TelemetryFrame::default()); + frames[write] = std::mem::take(&mut frames[read]); } } else { write += 1; diff --git a/src/telemetry_frame.rs b/src/telemetry_frame.rs index 49d9b4e..33883f5 100644 --- a/src/telemetry_frame.rs +++ b/src/telemetry_frame.rs @@ -1,12 +1,27 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . //! Generic telemetry frame model — unified representation of parsed sim racing data. //! //! Both the KSUDP (port 9996) and Telemetry Tool (port 10101) parsers produce //! `TelemetryFrame` instances from their raw binary data. -use serde::Serialize; +use serde::{Deserialize, Serialize}; /// Identifies which feed source produced this frame. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub enum FeedSource { Ksudp, TelemetryTool, @@ -20,7 +35,7 @@ pub const NUM_WHEELS: usize = 4; /// /// Fields present in both feeds are stored directly; fields unique to one feed /// are wrapped in `Option`. -#[derive(Debug, Clone, Serialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct TelemetryFrame { // ── Speed ────────────────────────────────────────────────────── pub speed_kmh: f32, @@ -121,6 +136,7 @@ pub struct TelemetryFrame { pub rain_density: Option, pub track_length: Option, pub full_position: Option<[f32; 3]>, + pub current_lap_distance: Option, pub tyre_wear: Option<[u8; 4]>, pub brake_temp_celsius: Option<[i16; 4]>, pub suspension_damage: Option<[u8; 4]>, @@ -211,6 +227,7 @@ impl Default for TelemetryFrame { rain_density: None, track_length: None, full_position: None, + current_lap_distance: None, tyre_wear: None, brake_temp_celsius: None, suspension_damage: None, diff --git a/src/track_model.rs b/src/track_model.rs new file mode 100644 index 0000000..28e5015 --- /dev/null +++ b/src/track_model.rs @@ -0,0 +1,229 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +//! Persistent track model data structure for track mapping and analysis. +//! +//! Stores the track geometry (center line, boundaries, corners, sectors) +//! keyed by (game, track_name). Files are stored at data/tracks//.json. + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +/// A corner detected from curvature analysis. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Corner { + /// Index into the center_line array where this corner starts. + pub index: usize, + /// Corner number (1-based, sequential around the track). + pub number: u32, + /// Spline distance at corner entry. + pub entry_s: f64, + /// Spline distance at the apex (peak curvature). + pub apex_s: f64, + /// Spline distance at corner exit. + pub exit_s: f64, + /// Peak curvature value at the apex. + pub curvature_peak: f64, +} + +/// A track sector (typically 3 per track). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Sector { + /// Sector number (0-based). + pub index: u32, + /// Spline distance at sector start. + pub start_s: f64, + /// Spline distance at sector end. + pub end_s: f64, +} + +/// How the track model was created. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum TrackModelSource { + /// Created from deliberate boundary recording (2 slow laps). + BoundaryRecording, + /// Auto-estimated from normal driving data. + AutoEstimated, +} + +/// A persisted track model with full geometry, corners, and sectors. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TrackModel { + /// Game identifier (e.g., "assetto_corsa", "project_cars_2"). + pub game: String, + /// Track name (e.g., "ks_nordschleife", "monza"). + pub track_name: String, + /// Center line points as normalized (x, z) pairs. + /// These are 2D coordinates suitable for Canvas rendering. + pub center_line: Vec<(f64, f64)>, + /// Left boundary points. + pub left_boundary: Vec<(f64, f64)>, + /// Right boundary points. + pub right_boundary: Vec<(f64, f64)>, + /// Track width at each center_line point (meters or normalized units). + pub track_width: Vec, + /// Heading direction at each center_line point (radians, 0=east, pi/2=north). + pub heading: Vec, + /// Curvature κ(s) at each center_line point (1/radius). + pub curvature: Vec, + /// Detected corners. + pub corners: Vec, + /// Track sectors. + pub sectors: Vec, + /// How the model was created. + pub source: TrackModelSource, + /// ISO 8601 timestamp when the model was created. + pub created_at: String, +} + +/// Summary info for listing track models (without full geometry). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TrackSummary { + pub game: String, + pub track_name: String, + pub source: TrackModelSource, + pub created_at: String, + pub corner_count: usize, +} + +fn is_safe_path_component(s: &str) -> bool { + !s.is_empty() && !s.contains('/') && !s.contains('\\') && !s.contains("..") && s != "." +} + +/// Manages persistent TrackModel storage on disk. +pub struct TrackModelStore { + tracks_dir: PathBuf, +} + +impl TrackModelStore { + /// Create a new store. The tracks directory will be at `data_dir/tracks/`. + pub fn new(data_dir: &Path) -> Self { + Self { + tracks_dir: data_dir.join("tracks"), + } + } + + /// Get the file path for a track model. + fn track_path(&self, game: &str, track_name: &str) -> std::io::Result { + if !is_safe_path_component(game) || !is_safe_path_component(track_name) { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "Invalid game or track_name: contains path traversal characters", + )); + } + Ok(self.tracks_dir.join(game).join(format!("{}.json", track_name))) + } + + /// List all stored track models. + pub async fn list(&self) -> std::io::Result> { + let mut summaries = Vec::new(); + if !self.tracks_dir.exists() { + return Ok(summaries); + } + + let mut game_entries = tokio::fs::read_dir(&self.tracks_dir).await?; + while let Some(game_entry) = game_entries.next_entry().await? { + let game_path = game_entry.path(); + if !game_path.is_dir() { + continue; + } + let _game = game_path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_string(); + + let mut track_entries = tokio::fs::read_dir(&game_path).await?; + while let Some(track_entry) = track_entries.next_entry().await? { + let track_path = track_entry.path(); + if track_path.extension().and_then(|e| e.to_str()) != Some("json") { + continue; + } + let _track_name = track_path + .file_stem() + .and_then(|n| n.to_str()) + .unwrap_or("") + .to_string(); + + match tokio::fs::read_to_string(&track_path).await { + Ok(json) => { + if let Ok(model) = serde_json::from_str::(&json) { + summaries.push(TrackSummary { + game: model.game.clone(), + track_name: model.track_name.clone(), + source: model.source, + created_at: model.created_at, + corner_count: model.corners.len(), + }); + } + } + Err(e) => { + eprintln!( + "[WARN] Failed to read track model {}: {}", + track_path.display(), + e + ); + } + } + } + } + + summaries.sort_by(|a, b| b.created_at.cmp(&a.created_at)); + Ok(summaries) + } + + /// Load a specific track model. + pub async fn load(&self, game: &str, track_name: &str) -> std::io::Result { + let path = self.track_path(game, track_name)?; + let json = tokio::fs::read_to_string(&path).await?; + serde_json::from_str(&json).map_err(|e| { + std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("Failed to parse track model: {}", e), + ) + }) + } + + /// Save a track model. Creates parent directories as needed. + pub async fn save(&self, model: &TrackModel) -> std::io::Result<()> { + let path = self.track_path(&model.game, &model.track_name)?; + if let Some(parent) = path.parent() { + tokio::fs::create_dir_all(parent).await?; + } + let json = serde_json::to_string_pretty(model)?; + tokio::fs::write(&path, json).await + } + + /// Delete a track model. + pub async fn delete(&self, game: &str, track_name: &str) -> std::io::Result<()> { + let path = self.track_path(game, track_name)?; + if !path.exists() { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + "Track model not found", + )); + } + tokio::fs::remove_file(&path).await + } + + /// Check if a track model exists. + #[allow(dead_code)] + pub async fn exists(&self, game: &str, track_name: &str) -> bool { + self.track_path(game, track_name) + .map(|p| p.exists()) + .unwrap_or(false) + } +} diff --git a/src/ui.rs b/src/ui.rs index a377e37..42c5664 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . use std::sync::{Arc, Mutex}; use ratatui::{ diff --git a/src/warnings.rs b/src/warnings.rs index f5cbfdf..906d193 100644 --- a/src/warnings.rs +++ b/src/warnings.rs @@ -1,3 +1,18 @@ +// rusty-telemetry — Sim racing telemetry analysis platform +// Copyright (C) 2026 Jan-Peter v. Hunnius +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero 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 Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . use std::collections::VecDeque; use std::sync::{Arc, Mutex}; use std::time::Instant;