summaryrefslogtreecommitdiff
path: root/service/src/com/android/telephony/imsmedia/lib/libimsmedia/core/nodes/RtpEncoderNode.cpp
blob: 944af9560c7f1dc937120a6ebd912eb581c8f7d8 (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
/**
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <RtpEncoderNode.h>
#include <ImsMediaTimer.h>
#include <ImsMediaTrace.h>
#include <ImsMediaVideoUtil.h>
#include <AudioConfig.h>
#include <VideoConfig.h>
#include <TextConfig.h>
#include <string.h>

RtpEncoderNode::RtpEncoderNode(BaseSessionCallback* callback) :
        BaseNode(callback)
{
    mRtpSession = nullptr;
    mDTMFMode = false;
    mMark = false;
    mPrevTimestamp = 0;
    mSamplingRate = 0;
    mRtpPayloadTx = 0;
    mRtpPayloadRx = 0;
    mRtpTxDtmfPayload = 0;
    mRtpRxDtmfPayload = 0;
    mDtmfSamplingRate = 0;
    mCvoValue = CVO_DEFINE_NONE;
    mRedundantLevel = 0;
    mRedundantPayload = 0;
}

RtpEncoderNode::~RtpEncoderNode()
{
    // remove IRtpSession here to avoid shared instance in other node from unable to use
    if (mRtpSession)
    {
        mRtpSession->StopRtp();
        mRtpSession->SetRtpEncoderListener(nullptr);
        IRtpSession::ReleaseInstance(mRtpSession);
        mRtpSession = nullptr;
    }
}

kBaseNodeId RtpEncoderNode::GetNodeId()
{
    return kNodeIdRtpEncoder;
}

ImsMediaResult RtpEncoderNode::Start()
{
    IMLOGD1("[Start] type[%d]", mMediaType);

    if (mRtpPayloadTx == 0 || mRtpPayloadRx == 0)
    {
        IMLOGE0("[Start] invalid payload number");
        return RESULT_INVALID_PARAM;
    }

    if (mRtpSession == nullptr)
    {
        mRtpSession = IRtpSession::GetInstance(mMediaType, mLocalAddress, mPeerAddress);

        if (mRtpSession == nullptr)
        {
            IMLOGE0("[Start] Can't create rtp session");
            return RESULT_NOT_READY;
        }
    }

    mRtpSession->SetRtpEncoderListener(this);

    if (mMediaType == IMS_MEDIA_AUDIO)
    {
        mRtpSession->SetRtpPayloadParam(mRtpPayloadTx, mRtpPayloadRx, mSamplingRate * 1000,
                mRtpTxDtmfPayload, mRtpRxDtmfPayload, mDtmfSamplingRate * 1000);
    }
    else if (mMediaType == IMS_MEDIA_VIDEO)
    {
        mRtpSession->SetRtpPayloadParam(mRtpPayloadTx, mRtpPayloadRx, mSamplingRate * 1000);
    }
    else if (mMediaType == IMS_MEDIA_TEXT)
    {
        if (mRedundantPayload > 0)
        {
            mRtpSession->SetRtpPayloadParam(mRtpPayloadTx, mRtpPayloadRx, mSamplingRate * 1000,
                    mRedundantPayload, mSamplingRate * 1000);
        }
        else
        {
            mRtpSession->SetRtpPayloadParam(mRtpPayloadTx, mRtpPayloadRx, mSamplingRate * 1000);
        }
    }

    mRtpSession->StartRtp();
    mDTMFMode = false;
    mMark = true;
    mPrevTimestamp = 0;
#ifdef DEBUG_JITTER_GEN_SIMULATION_DELAY
    mNextTime = 0;
#endif
#ifdef DEBUG_JITTER_GEN_SIMULATION_REORDER
    jitterData.Clear();
    mReorderDataCount = 0;
#endif
    mNodeState = kNodeStateRunning;
    return RESULT_SUCCESS;
}

void RtpEncoderNode::Stop()
{
    IMLOGD1("[Stop] type[%d]", mMediaType);
    std::lock_guard<std::mutex> guard(mMutex);

    if (mRtpSession)
    {
        mRtpSession->StopRtp();
    }

    ClearDataQueue();
    mNodeState = kNodeStateStopped;
}

void RtpEncoderNode::ProcessData()
{
    std::lock_guard<std::mutex> guard(mMutex);

    if (mNodeState != kNodeStateRunning)
    {
        return;
    }

    ImsMediaSubType subtype;
    uint8_t* data = nullptr;
    uint32_t size = 0;
    uint32_t timestamp = 0;
    bool mark = false;
    uint32_t seq = 0;
    ImsMediaSubType datatype;
    uint32_t arrivalTime = 0;

    if (GetData(&subtype, &data, &size, &timestamp, &mark, &seq, &datatype, &arrivalTime))
    {
        if (mMediaType == IMS_MEDIA_AUDIO)
        {
            if (!ProcessAudioData(subtype, data, size))
            {
                return;
            }
        }
        else if (mMediaType == IMS_MEDIA_VIDEO)
        {
            ProcessVideoData(subtype, data, size, timestamp, mark);
        }
        else if (mMediaType == IMS_MEDIA_TEXT)
        {
            ProcessTextData(subtype, data, size, timestamp, mark);
        }

        DeleteData();
    }
}

bool RtpEncoderNode::IsRunTime()
{
    return false;
}

bool RtpEncoderNode::IsSourceNode()
{
    return false;
}

void RtpEncoderNode::SetConfig(void* config)
{
    IMLOGD1("[SetConfig] media[%d]", mMediaType);

    if (config == nullptr)
    {
        return;
    }

    if (mMediaType == IMS_MEDIA_AUDIO)
    {
        AudioConfig* pConfig = reinterpret_cast<AudioConfig*>(config);
        mPeerAddress = RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort());
        mSamplingRate = pConfig->getSamplingRateKHz();
        mRtpPayloadTx = pConfig->getTxPayloadTypeNumber();
        mRtpPayloadRx = pConfig->getRxPayloadTypeNumber();
        mRtpTxDtmfPayload = pConfig->getTxDtmfPayloadTypeNumber();
        mRtpRxDtmfPayload = pConfig->getRxDtmfPayloadTypeNumber();
        mDtmfSamplingRate = pConfig->getDtmfsamplingRateKHz();
    }
    else if (mMediaType == IMS_MEDIA_VIDEO)
    {
        VideoConfig* pConfig = reinterpret_cast<VideoConfig*>(config);
        mPeerAddress = RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort());
        mSamplingRate = pConfig->getSamplingRateKHz();
        mRtpPayloadTx = pConfig->getTxPayloadTypeNumber();
        mRtpPayloadRx = pConfig->getRxPayloadTypeNumber();
        mCvoValue = pConfig->getCvoValue();
    }
    else if (mMediaType == IMS_MEDIA_TEXT)
    {
        TextConfig* pConfig = reinterpret_cast<TextConfig*>(config);
        mPeerAddress = RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort());
        mSamplingRate = pConfig->getSamplingRateKHz();
        mRtpPayloadTx = pConfig->getTxPayloadTypeNumber();
        mRtpPayloadRx = pConfig->getRxPayloadTypeNumber();
        mRedundantPayload = pConfig->getRedundantPayload();
        mRedundantLevel = pConfig->getRedundantLevel();
    }

    IMLOGD2("[SetConfig] peer Ip[%s], port[%d]", mPeerAddress.ipAddress, mPeerAddress.port);
}

bool RtpEncoderNode::IsSameConfig(void* config)
{
    if (config == nullptr)
    {
        return true;
    }

    if (mMediaType == IMS_MEDIA_AUDIO)
    {
        AudioConfig* pConfig = reinterpret_cast<AudioConfig*>(config);
        return (mPeerAddress ==
                        RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort()) &&
                mSamplingRate == pConfig->getSamplingRateKHz() &&
                mRtpPayloadTx == pConfig->getTxPayloadTypeNumber() &&
                mRtpPayloadRx == pConfig->getRxPayloadTypeNumber() &&
                mRtpTxDtmfPayload == pConfig->getTxDtmfPayloadTypeNumber() &&
                mRtpRxDtmfPayload == pConfig->getRxDtmfPayloadTypeNumber() &&
                mDtmfSamplingRate == pConfig->getDtmfsamplingRateKHz());
    }
    else if (mMediaType == IMS_MEDIA_VIDEO)
    {
        VideoConfig* pConfig = reinterpret_cast<VideoConfig*>(config);
        return (mPeerAddress ==
                        RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort()) &&
                mSamplingRate == pConfig->getSamplingRateKHz() &&
                mRtpPayloadTx == pConfig->getTxPayloadTypeNumber() &&
                mRtpPayloadRx == pConfig->getRxPayloadTypeNumber() &&
                mCvoValue == pConfig->getCvoValue());
    }
    else if (mMediaType == IMS_MEDIA_TEXT)
    {
        TextConfig* pConfig = reinterpret_cast<TextConfig*>(config);
        return (mPeerAddress ==
                        RtpAddress(pConfig->getRemoteAddress().c_str(), pConfig->getRemotePort()) &&
                mSamplingRate == pConfig->getSamplingRateKHz() &&
                mRtpPayloadTx == pConfig->getTxPayloadTypeNumber() &&
                mRtpPayloadRx == pConfig->getRxPayloadTypeNumber() &&
                mRedundantPayload == pConfig->getRedundantPayload() &&
                mRedundantLevel == pConfig->getRedundantLevel());
    }

    return false;
}

void RtpEncoderNode::OnRtpPacket(unsigned char* data, uint32_t nSize)
{
    SendDataToRearNode(MEDIASUBTYPE_RTPPACKET, data, nSize, 0, 0, 0);
}

void RtpEncoderNode::SetLocalAddress(const RtpAddress& address)
{
    mLocalAddress = address;
}

void RtpEncoderNode::SetPeerAddress(const RtpAddress& address)
{
    mPeerAddress = address;
}

bool RtpEncoderNode::SetCvoExtension(const int64_t facing, const int64_t orientation)
{
    IMLOGD3("[SetCvoExtension] cvoValue[%d], facing[%ld], orientation[%ld]", mCvoValue, facing,
            orientation);

    if (mCvoValue != -1)
    {
        uint32_t rotation = 0;
        uint32_t cameraId = 0;

        if (facing == kCameraFacingRear)
        {
            cameraId = 1;
        }

        switch (orientation)
        {
            default:
            case 0:
                rotation = 0;
                break;
            case 270:
                rotation = 1;
                break;
            case 180:
                rotation = 2;
                break;
            case 90:
                rotation = 3;
                break;
        }

        if (cameraId == 1)  // rear camera
        {
            if (rotation == 1)  // CCW90
            {
                rotation = 3;
            }
            else if (rotation == 3)  // CCW270
            {
                rotation = 1;
            }
        }

        int8_t extensionData[4];  // 32bit
        IMLOGD3("[SetCvoExtension] cvoValue[%d], facing[%d], orientation[%d]", mCvoValue, cameraId,
                rotation);

        extensionData[0] = (mCvoValue << 4) | 1;  // local identifier and data length
        extensionData[1] = (cameraId << 3) | rotation;
        extensionData[2] = 0;  // padding
        extensionData[3] = 0;  // padding

        mListRtpExtension.clear();
        mListRtpExtension.push_back(RtpHeaderExtensionInfo(
                RtpHeaderExtensionInfo::kBitPatternForOneByteHeader, 1, extensionData, 4));
        return true;
    }

    return false;
}

void RtpEncoderNode::SetRtpHeaderExtension(std::list<RtpHeaderExtension>* listExtension)
{
    if (listExtension == nullptr || listExtension->empty())
    {
        return;
    }

    /**
     * Check number of byte of the header. Based on RFC8285 4.2, one byte header has a local
     * identifier in range of 1 to 14. Two byte header has is a range of 1 to 255.
     */
    bool useTwoByteHeader = false;
    int32_t totalPayloadLength = 0;  // accumulate payload length except the header size

    for (auto extension : *listExtension)
    {
        if (extension.getLocalIdentifier() > 15)
        {
            useTwoByteHeader = true;
        }

        totalPayloadLength += extension.getExtensionDataSize();
    }

    // accumulate header size
    useTwoByteHeader ? totalPayloadLength += 2 * listExtension->size()
                     : totalPayloadLength += listExtension->size();

    // padding size
    int32_t paddingSize = totalPayloadLength % IMS_MEDIA_WORD_SIZE == 0
            ? 0
            : IMS_MEDIA_WORD_SIZE - totalPayloadLength % IMS_MEDIA_WORD_SIZE;
    totalPayloadLength += paddingSize;

    int8_t* extensionData = new int8_t[totalPayloadLength];
    int offset = 0;

    for (auto extension : *listExtension)
    {
        if (useTwoByteHeader)
        {
            extensionData[offset++] = extension.getLocalIdentifier();
            extensionData[offset++] = extension.getExtensionDataSize();
        }
        else
        {
            extensionData[offset++] =
                    extension.getLocalIdentifier() << 4 | (extension.getExtensionDataSize() - 1);
        }

        memcpy(extensionData + offset, extension.getExtensionData(),
                extension.getExtensionDataSize());
        offset += extension.getExtensionDataSize();
    }

    // add padding
    memset(extensionData + offset, 0, paddingSize);

    IMLOGD3("[SetRtpHeaderExtension] twoByte[%d], size[%d], list size[%d]", useTwoByteHeader,
            totalPayloadLength, listExtension->size());

    int16_t defineByProfile = useTwoByteHeader
            ? RtpHeaderExtensionInfo::kBitPatternForTwoByteHeader
            : RtpHeaderExtensionInfo::kBitPatternForOneByteHeader;
    mListRtpExtension.push_back(RtpHeaderExtensionInfo(
            defineByProfile, totalPayloadLength / 4, extensionData, totalPayloadLength));

    delete[] extensionData;
}

bool RtpEncoderNode::ProcessAudioData(ImsMediaSubType subtype, uint8_t* data, uint32_t size)
{
    uint32_t currentTimestamp;
    uint32_t timeDiff;
    uint32_t timestampDiff;

    if (subtype == MEDIASUBTYPE_DTMFSTART)
    {
        IMLOGD0("[ProcessAudioData] SetDTMF mode true");
        mDTMFMode = true;
        mMark = true;
    }
    else if (subtype == MEDIASUBTYPE_DTMFEND)
    {
        IMLOGD0("[ProcessAudioData] SetDTMF mode false");
        mDTMFMode = false;
        mMark = true;
    }
    else if (subtype == MEDIASUBTYPE_DTMF_PAYLOAD)
    {
        if (mDTMFMode)
        {
            currentTimestamp = ImsMediaTimer::GetTimeInMilliSeconds();
            timeDiff = currentTimestamp - mPrevTimestamp;

            if (timeDiff < 20)
            {
                return false;
            }

            mPrevTimestamp = currentTimestamp;
            timestampDiff = timeDiff * mSamplingRate;

            IMLOGD_PACKET2(IM_PACKET_LOG_RTP, "[ProcessAudioData] dtmf payload, size[%u], TS[%u]",
                    size, currentTimestamp);
            mRtpSession->SendRtpPacket(
                    mRtpTxDtmfPayload, data, size, currentTimestamp, mMark, timestampDiff);

            if (mMark)
            {
                mMark = false;
            }
        }
    }
    else  // MEDIASUBTYPE_RTPPAYLOAD
    {
        if (mDTMFMode == false)
        {
            currentTimestamp = ImsMediaTimer::GetTimeInMilliSeconds();

            if (mPrevTimestamp == 0)
            {
                timeDiff = 0;
                mPrevTimestamp = currentTimestamp;
            }
            else
            {
                timeDiff = ((currentTimestamp - mPrevTimestamp) + 5) / 20 * 20;

                if (timeDiff > 20)
                {
                    mPrevTimestamp = currentTimestamp;
                }
                else if (timeDiff == 0)
                {
                    return false;
                }
                else
                {
                    mPrevTimestamp += timeDiff;
                }
            }

            RtpPacket* packet = new RtpPacket();
            packet->rtpDataType = kRtpDataTypeNormal;
            mCallback->SendEvent(
                    kCollectPacketInfo, kStreamRtpTx, reinterpret_cast<uint64_t>(packet));

            timestampDiff = timeDiff * mSamplingRate;
            IMLOGD_PACKET3(IM_PACKET_LOG_RTP, "[ProcessAudioData] PayloadTx[%d], Size[%d], TS[%d]",
                    mRtpPayloadTx, size, currentTimestamp);

            if (!mListRtpExtension.empty())
            {
                mRtpSession->SendRtpPacket(mRtpPayloadTx, data, size, currentTimestamp, mMark,
                        timestampDiff, &mListRtpExtension.front());
                mListRtpExtension.pop_front();
            }
            else
            {
                mRtpSession->SendRtpPacket(
                        mRtpPayloadTx, data, size, currentTimestamp, mMark, timestampDiff);
            }

            if (mMark)
            {
                mMark = false;
            }
        }
    }

    return true;
}

void RtpEncoderNode::ProcessVideoData(
        ImsMediaSubType subtype, uint8_t* data, uint32_t size, uint32_t timestamp, bool mark)
{
    IMLOGD_PACKET4(IM_PACKET_LOG_RTP, "[ProcessVideoData] subtype[%d], size[%d], TS[%u], mark[%d]",
            subtype, size, timestamp, mark);

#ifdef SIMULATE_VIDEO_CVO_UPDATE
    const int64_t kCameraFacing = kCameraFacingFront;
    static int64_t sDeviceOrientation = 0;
    static int64_t sCount = 0;
    if ((++sCount % 100) == 0)
    {
        SetCvoExtension(kCameraFacing, (sDeviceOrientation += 90) % 360);
    }
#endif

    if (mCvoValue > 0 && mark && subtype == MEDIASUBTYPE_VIDEO_IDR_FRAME)
    {
        mRtpSession->SendRtpPacket(mRtpPayloadTx, data, size, timestamp, mark, 0,
                mListRtpExtension.empty() ? nullptr : &mListRtpExtension.front());
    }
    else
    {
        mRtpSession->SendRtpPacket(mRtpPayloadTx, data, size, timestamp, mark, 0);
    }
}

void RtpEncoderNode::ProcessTextData(
        ImsMediaSubType subtype, uint8_t* data, uint32_t size, uint32_t timestamp, bool mark)
{
    IMLOGD_PACKET4(IM_PACKET_LOG_RTP,
            "[ProcessTextData] subtype[%d], size[%d], timestamp[%d], mark[%d]", subtype, size,
            timestamp, mark);

    uint32_t timeDiff;

    if (mMark == true)
    {
        timeDiff = 0;
    }
    else
    {
        timeDiff = timestamp - mPrevTimestamp;
    }

    if (subtype == MEDIASUBTYPE_BITSTREAM_T140)
    {
        if (mRedundantLevel > 1 && mRedundantPayload > 0)
        {
            mRtpSession->SendRtpPacket(mRedundantPayload, data, size, timestamp, mark, timeDiff);
        }
        else
        {
            mRtpSession->SendRtpPacket(mRtpPayloadRx, data, size, timestamp, mark, timeDiff);
        }
    }
    else if (subtype == MEDIASUBTYPE_BITSTREAM_T140_RED)
    {
        mRtpSession->SendRtpPacket(mRtpPayloadTx, data, size, timestamp, mark, timeDiff);
    }

    mMark = false;
    mPrevTimestamp = timestamp;
}