aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/qt_sdl/LocalMP.cpp
blob: 906f4d4844ea141c065e6cac307f55c4ec3b8df3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*
    Copyright 2016-2023 melonDS team

    This file is part of melonDS.

    melonDS is free software: you can redistribute it and/or modify it under
    the terms of the GNU General Public License as published by the Free
    Software Foundation, either version 3 of the License, or (at your option)
    any later version.

    melonDS is distributed in the hope that it will be useful, but WITHOUT ANY
    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with melonDS. If not, see http://www.gnu.org/licenses/.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#ifdef __WIN32__
    #include <windows.h>
#else
    #include <fcntl.h>
    #include <semaphore.h>
    #include <time.h>
    #ifdef __APPLE__
        #include "sem_timedwait.h"
    #endif
#endif

#include <string>
#include <QSharedMemory>

#include "Config.h"
#include "LocalMP.h"
#include "Platform.h"

#include <stdint.h>
#include "../../vsr.h"

// utility: osdAddMessage
#include "Window.h"
extern MainWindow* mainWindow;

#ifdef VSR_DUMP_MESSAGES
#include <pcap/pcap.h>
#include <vector>
pcap_dumper_t* dumper;
#endif

#ifdef VSR_MESSAGE_FIDDLING
#include <time.h>
bool fiddle = false;
#endif

using namespace melonDS;
using namespace melonDS::Platform;

using Platform::Log;
using Platform::LogLevel;

namespace LocalMP
{

u32 MPUniqueID;
u8 PacketBuffer[2048];

struct MPQueueHeader
{
    u16 NumInstances;
    u16 InstanceBitmask;  // bitmask of all instances present
    u16 ConnectedBitmask; // bitmask of which instances are ready to send/receive packets
    u32 PacketWriteOffset;
    u32 ReplyWriteOffset;
    u16 MPHostInstanceID; // instance ID from which the last CMD frame was sent
    u16 MPReplyBitmask;   // bitmask of which clients replied in time
};

struct MPPacketHeader
{
    u32 Magic;
    u32 SenderID;
    u32 Type;       // 0=regular 1=CMD 2=reply 3=ack
    u32 Length;
    u64 Timestamp;
};

QSharedMemory* MPQueue;
int InstanceID;
u32 PacketReadOffset;
u32 ReplyReadOffset;

const u32 kQueueSize = 0x20000;
const u32 kMaxFrameSize = 0x800;
const u32 kPacketStart = sizeof(MPQueueHeader);
const u32 kReplyStart = kQueueSize / 2;
const u32 kPacketEnd = kReplyStart;
const u32 kReplyEnd = kQueueSize;

int RecvTimeout;

int LastHostID;


// we need to come up with our own abstraction layer for named semaphores
// because QSystemSemaphore doesn't support waiting with a timeout
// and, as such, is unsuitable to our needs

#ifdef __WIN32__

bool SemInited[32];
HANDLE SemPool[32];

void SemPoolInit()
{
    for (int i = 0; i < 32; i++)
    {
        SemPool[i] = INVALID_HANDLE_VALUE;
        SemInited[i] = false;
    }
}

void SemDeinit(int num);

void SemPoolDeinit()
{
    for (int i = 0; i < 32; i++)
        SemDeinit(i);
}

bool SemInit(int num)
{
    if (SemInited[num])
        return true;

    char semname[64];
    sprintf(semname, "Local\\melonNIFI_Sem%02d", num);

    HANDLE sem = CreateSemaphoreA(nullptr, 0, 64, semname);
    SemPool[num] = sem;
    SemInited[num] = true;
    return sem != INVALID_HANDLE_VALUE;
}

void SemDeinit(int num)
{
    if (SemPool[num] != INVALID_HANDLE_VALUE)
    {
        CloseHandle(SemPool[num]);
        SemPool[num] = INVALID_HANDLE_VALUE;
    }

    SemInited[num] = false;
}

bool SemPost(int num)
{
    SemInit(num);
    return ReleaseSemaphore(SemPool[num], 1, nullptr) != 0;
}

bool SemWait(int num, int timeout)
{
    return WaitForSingleObject(SemPool[num], timeout) == WAIT_OBJECT_0;
}

void SemReset(int num)
{
    while (WaitForSingleObject(SemPool[num], 0) == WAIT_OBJECT_0);
}

#else

bool SemInited[32];
sem_t* SemPool[32];

void SemPoolInit()
{
    for (int i = 0; i < 32; i++)
    {
        SemPool[i] = SEM_FAILED;
        SemInited[i] = false;
    }
}

void SemDeinit(int num);

void SemPoolDeinit()
{
    for (int i = 0; i < 32; i++)
        SemDeinit(i);
}

bool SemInit(int num)
{
    if (SemInited[num])
        return true;

    char semname[64];
    sprintf(semname, "/melonNIFI_Sem%02d", num);

    sem_t* sem = sem_open(semname, O_CREAT, 0644, 0);
    SemPool[num] = sem;
    SemInited[num] = true;
    return sem != SEM_FAILED;
}

void SemDeinit(int num)
{
    if (SemPool[num] != SEM_FAILED)
    {
        sem_close(SemPool[num]);
        SemPool[num] = SEM_FAILED;
    }

    SemInited[num] = false;
}

bool SemPost(int num)
{
    SemInit(num);
    return sem_post(SemPool[num]) == 0;
}

bool SemWait(int num, int timeout)
{
    if (!timeout)
        return sem_trywait(SemPool[num]) == 0;

    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_nsec += timeout * 1000000;
    long sec = ts.tv_nsec / 1000000000;
    ts.tv_nsec -= sec * 1000000000;
    ts.tv_sec += sec;

    return sem_timedwait(SemPool[num], &ts) == 0;
}

void SemReset(int num)
{
    while (sem_trywait(SemPool[num]) == 0);
}

#endif


bool Init()
{
    MPQueue = new QSharedMemory("melonNIFI");

    if (!MPQueue->attach())
    {
        Log(LogLevel::Info, "MP sharedmem doesn't exist. creating\n");
        if (!MPQueue->create(kQueueSize))
        {
            Log(LogLevel::Error, "MP sharedmem create failed :( (%d)\n", MPQueue->error());
            delete MPQueue;
            MPQueue = nullptr;
            return false;
        }

        MPQueue->lock();
        memset(MPQueue->data(), 0, MPQueue->size());
        MPQueueHeader* header = (MPQueueHeader*)MPQueue->data();
        header->PacketWriteOffset = kPacketStart;
        header->ReplyWriteOffset = kReplyStart;
        MPQueue->unlock();
    }

    MPQueue->lock();
    MPQueueHeader* header = (MPQueueHeader*)MPQueue->data();

    u16 mask = header->InstanceBitmask;
    for (int i = 0; i < 16; i++)
    {
        if (!(mask & (1<<i)))
        {
            InstanceID = i;
            header->InstanceBitmask |= (1<<i);
            //header->ConnectedBitmask |= (1 << i);
            break;
        }
    }
    header->NumInstances++;

    PacketReadOffset = header->PacketWriteOffset;
    ReplyReadOffset = header->ReplyWriteOffset;

    MPQueue->unlock();

    // prepare semaphores
    // semaphores 0-15: regular frames; semaphore I is posted when instance I needs to process a new frame
    // semaphores 16-31: MP replies; semaphore I is posted when instance I needs to process a new MP reply

    SemPoolInit();
    SemInit(InstanceID);
    SemInit(16+InstanceID);

    LastHostID = -1;

    Log(LogLevel::Info, "MP comm init OK, instance ID %d\n", InstanceID);

    RecvTimeout = 25;

#ifdef VSR_DUMP_MESSAGES
    pcap_t* handle = pcap_open_dead(DLT_USER0, 1 << 16);
    char filename[80];
    snprintf(filename, 79, "melon_%lu_instance_%d.pcap", time(NULL), InstanceID);
    mainWindow->osdAddMessage(0xffffff, "started dumping to %s", filename);
    dumper = pcap_dump_open(handle, filename);
#endif

    return true;
}

void DeInit()
{
#ifdef VSR_DUMP_MESSAGES
    pcap_dump_close(dumper);
#endif

    if (MPQueue)
    {
        MPQueue->lock();
        if (MPQueue->data() != nullptr)
        {
            MPQueueHeader *header = (MPQueueHeader *) MPQueue->data();
            header->ConnectedBitmask &= ~(1 << InstanceID);
            header->InstanceBitmask &= ~(1 << InstanceID);
            header->NumInstances--;
        }
        MPQueue->unlock();

        SemPoolDeinit();

        MPQueue->detach();
    }

    delete MPQueue;
    MPQueue = nullptr;
}

void SetRecvTimeout(int timeout)
{
    RecvTimeout = timeout;
}

void Begin()
{
    if (!MPQueue) return;
    MPQueue->lock();
    MPQueueHeader* header = (MPQueueHeader*)MPQueue->data();
    PacketReadOffset = header->PacketWriteOffset;
    ReplyReadOffset = header->ReplyWriteOffset;
    SemReset(InstanceID);
    SemReset(16+InstanceID);
    header->ConnectedBitmask |= (1 << InstanceID);
    MPQueue->unlock();
}

void End()
{
    if (!MPQueue) return;
    MPQueue->lock();
    MPQueueHeader* header = (MPQueueHeader*)MPQueue->data();
    //SemReset(InstanceID);
    //SemReset(16+InstanceID);
    header->ConnectedBitmask &= ~(1 << InstanceID);
    MPQueue->unlock();
}

void FIFORead(int fifo, void* buf, int len)
{
    u8* data = (u8*)MPQueue->data();

    u32 offset, start, end;
    if (fifo == 0)
    {
        offset = PacketReadOffset;
        start = kPacketStart;
        end = kPacketEnd;
    }
    else
    {
        offset = ReplyReadOffset;
        start = kReplyStart;
        end = kReplyEnd;
    }

    if ((offset + len) >= end)
    {
        u32 part1 = end - offset;
        memcpy(buf, &data[offset], part1);
        memcpy(&((u8*)buf)[part1], &data[start], len - part1);
        offset = start + len - part1;
    }
    else
    {
        memcpy(buf, &data[offset], len);
        offset += len;
    }

    if (fifo == 0) PacketReadOffset = offset;
    else           ReplyReadOffset = offset;
}

void FIFOWrite(int fifo, void* buf, int len)
{
    u8* data = (u8*)MPQueue->data();
    MPQueueHeader* header = (MPQueueHeader*)&data[0];

    u32 offset, start, end;
    if (fifo == 0)
    {
        offset = header->PacketWriteOffset;
        start = kPacketStart;
        end = kPacketEnd;
    }
    else
    {
        offset = header->ReplyWriteOffset;
        start = kReplyStart;
        end = kReplyEnd;
    }

    if ((offset + len) >= end)
    {
        u32 part1 = end - offset;
        memcpy(&data[offset], buf, part1);
        memcpy(&data[start], &((u8*)buf)[part1], len - part1);
        offset = start + len - part1;
    }
    else
    {
        memcpy(&data[offset], buf, len);
        offset += len;
    }

    if (fifo == 0) header->PacketWriteOffset = offset;
    else           header->ReplyWriteOffset = offset;
}

int SendPacketGeneric(u32 type, u8* packet, int len, u64 timestamp)
{
    if (!MPQueue) return 0;
    MPQueue->lock();
    u8* data = (u8*)MPQueue->data();
    MPQueueHeader* header = (MPQueueHeader*)&data[0];

    u16 mask = header->ConnectedBitmask;

    // TODO: check if the FIFO is full!

    MPPacketHeader pktheader;
    pktheader.Magic = 0x4946494E;
    pktheader.SenderID = InstanceID;
    pktheader.Type = type;
    pktheader.Length = len;
    pktheader.Timestamp = timestamp;

#ifdef VSR_MESSAGE_FIDDLING
    static int package_idx = 0;
#endif

    type &= 0xFFFF;
    int nfifo = (type == 2) ? 1 : 0;
    // NOTE: this is the ni-fi packet header, altering this header in any way
    // seems to consistently trigger PACKET FIFO OVERFLOW errors
    FIFOWrite(nfifo, &pktheader, sizeof(pktheader));
#ifdef VSR_DUMP_MESSAGES
    std::vector<uint8_t> buf;
    buf.insert(buf.end(), (uint8_t*) &pktheader, (uint8_t*) &pktheader + sizeof(pktheader));
#endif
    if (len)
    {
#ifdef VSR_MESSAGE_FIDDLING
        // if message packet (has size 222 w/o ni-fi header)
        if (fiddle && len == 222) {
            // if fresh message (do not count resends)
            if (packet[0x02] == 0x02) {
                // corrupt all pixels in every nth package
                package_idx = (package_idx + 1) % 10;
            }

            if (true || package_idx == 0) {
                // mainWindow->osdAddMessage(0x00ff00, "oops!");
                // NOTE: packet indexes are after NIFI header!
                for (size_t i = 0; i < 0x80; i++) {
                    packet[0x3e + i] = 0x11;
                }
                // packet[0x3e + 0x00] = 0x13;
                // packet[0x3e + 0x01] = 0x13;

                // packet[0x3e + 0x02] = 0x33;
                // packet[0x3e + 0x04] = 0x33;
            }
        }
#endif

#ifdef VSR_DUMP_MESSAGES
        buf.insert(buf.end(), (uint8_t*) packet, (uint8_t*) packet + len);
#endif
        FIFOWrite(nfifo, packet, len);
    }

#ifdef VSR_DUMP_MESSAGES
    struct pcap_pkthdr p;
    p.len = buf.size();
    p.caplen = buf.size();
    gettimeofday(&p.ts, NULL);
    pcap_dump((u_char*) dumper, &p, buf.data());
#endif

    if (type == 1)
    {
        // NOTE: this is not guarded against, say, multiple multiplay games happening on the same machine
        // we would need to pass the packet's SenderID through the wifi module for that
        header->MPHostInstanceID = InstanceID;
        header->MPReplyBitmask = 0;
        ReplyReadOffset = header->ReplyWriteOffset;
        SemReset(16 + InstanceID);
    }
    else if (type == 2)
    {
        header->MPReplyBitmask |= (1 << InstanceID);
    }

    MPQueue->unlock();

    if (type == 2)
    {
        SemPost(16 + header->MPHostInstanceID);
    }
    else
    {
        for (int i = 0; i < 16; i++)
        {
            if (mask & (1<<i))
                SemPost(i);
        }
    }

    return len;
}

int RecvPacketGeneric(u8* packet, bool block, u64* timestamp)
{
#ifdef VSR_DUMP_MESSAGES
    std::vector<uint8_t> buf;
#endif

    if (!MPQueue) return 0;
    for (;;)
    {
        if (!SemWait(InstanceID, block ? RecvTimeout : 0))
        {
            return 0;
        }

        MPQueue->lock();
        u8* data = (u8*)MPQueue->data();
        MPQueueHeader* header = (MPQueueHeader*)&data[0];

        MPPacketHeader pktheader;
        FIFORead(0, &pktheader, sizeof(pktheader));

        if (pktheader.Magic != 0x4946494E)
        {
            Log(LogLevel::Warn, "PACKET FIFO OVERFLOW\n");
            PacketReadOffset = header->PacketWriteOffset;
            SemReset(InstanceID);
            MPQueue->unlock();
            return 0;
        }

        if (pktheader.SenderID == InstanceID)
        {
            // skip this packet
            PacketReadOffset += pktheader.Length;
            if (PacketReadOffset >= kPacketEnd)
                PacketReadOffset += kPacketStart - kPacketEnd;

            MPQueue->unlock();
            continue;
        }

#ifdef VSR_DUMP_MESSAGES
        buf.insert(buf.end(), (uint8_t*) &pktheader, (uint8_t*) &pktheader + sizeof(pktheader));
#endif

        if (pktheader.Length)
        {
            FIFORead(0, packet, pktheader.Length);

#ifdef VSR_DUMP_MESSAGES
            buf.insert(buf.end(), (uint8_t*) packet, (uint8_t*) packet + pktheader.Length);
#endif

            if (pktheader.Type == 1)
                LastHostID = pktheader.SenderID;
        }

        if (timestamp) *timestamp = pktheader.Timestamp;
        MPQueue->unlock();

#ifdef VSR_DUMP_MESSAGES
        struct pcap_pkthdr p;
        p.len = buf.size();
        p.caplen = buf.size();
        gettimeofday(&p.ts, NULL);
        pcap_dump((u_char*) dumper, &p, buf.data());
#endif

        return pktheader.Length;
    }
}

int SendPacket(u8* packet, int len, u64 timestamp)
{
    return SendPacketGeneric(0, packet, len, timestamp);
}

int RecvPacket(u8* packet, u64* timestamp)
{
    return RecvPacketGeneric(packet, false, timestamp);
}


int SendCmd(u8* packet, int len, u64 timestamp)
{
    return SendPacketGeneric(1, packet, len, timestamp);
}

int SendReply(u8* packet, int len, u64 timestamp, u16 aid)
{
    return SendPacketGeneric(2 | (aid<<16), packet, len, timestamp);
}

int SendAck(u8* packet, int len, u64 timestamp)
{
    return SendPacketGeneric(3, packet, len, timestamp);
}

int RecvHostPacket(u8* packet, u64* timestamp)
{
    if (!MPQueue) return -1;

    if (LastHostID != -1)
    {
        // check if the host is still connected

        MPQueue->lock();
        u8* data = (u8*)MPQueue->data();
        MPQueueHeader* header = (MPQueueHeader*)&data[0];
        u16 curinstmask = header->ConnectedBitmask;
        MPQueue->unlock();

        if (!(curinstmask & (1 << LastHostID)))
            return -1;
    }

    return RecvPacketGeneric(packet, true, timestamp);
}

u16 RecvReplies(u8* packets, u64 timestamp, u16 aidmask)
{
    if (!MPQueue) return 0;

    u16 ret = 0;
    u16 myinstmask = (1 << InstanceID);
    u16 curinstmask;

    {
        MPQueue->lock();
        u8* data = (u8*)MPQueue->data();
        MPQueueHeader* header = (MPQueueHeader*)&data[0];
        curinstmask = header->ConnectedBitmask;
        MPQueue->unlock();
    }

    // if all clients have left: return early
    if ((myinstmask & curinstmask) == curinstmask)
        return 0;

    for (;;)
    {
        if (!SemWait(16+InstanceID, RecvTimeout))
        {
            // no more replies available
            return ret;
        }

        MPQueue->lock();
        u8* data = (u8*)MPQueue->data();
        MPQueueHeader* header = (MPQueueHeader*)&data[0];

        MPPacketHeader pktheader;
        FIFORead(1, &pktheader, sizeof(pktheader));

        if (pktheader.Magic != 0x4946494E)
        {
            Log(LogLevel::Warn, "REPLY FIFO OVERFLOW\n");
            ReplyReadOffset = header->ReplyWriteOffset;
            SemReset(16+InstanceID);
            MPQueue->unlock();
            return 0;
        }

        if ((pktheader.SenderID == InstanceID) || // packet we sent out (shouldn't happen, but hey)
            (pktheader.Timestamp < (timestamp - 32))) // stale packet
        {
            // skip this packet
            ReplyReadOffset += pktheader.Length;
            if (ReplyReadOffset >= kReplyEnd)
                ReplyReadOffset += kReplyStart - kReplyEnd;

            MPQueue->unlock();
            continue;
        }

        if (pktheader.Length)
        {
            u32 aid = (pktheader.Type >> 16);
            FIFORead(1, &packets[(aid-1)*1024], pktheader.Length);
            ret |= (1 << aid);
        }

        myinstmask |= (1 << pktheader.SenderID);
        if (((myinstmask & curinstmask) == curinstmask) ||
            ((ret & aidmask) == aidmask))
        {
            // all the clients have sent their reply

            MPQueue->unlock();
            return ret;
        }

        MPQueue->unlock();
    }
}

}