Ticket #7053: RTPGenerator.cpp

File RTPGenerator.cpp, 28.5 KB (added by chacha, 9 years ago)
Line 
1#if !defined(WIN32) && defined(_MSC_VER)
2#define WIN32
3#endif
4
5#ifdef WIN32
6#define NOMINMAX
7#include <Winsock2.h>
8#include <Ws2tcpip.h>
9#include <iphlpapi.h>
10#define _USE_MATH_DEFINES
11#else
12#include <arpa/inet.h>
13#include <ifaddrs.h>
14#include <net/if.h>
15#include <netinet/in.h>
16#include <sys/ioctl.h>
17#include <sys/socket.h>
18#include <sys/types.h>
19#include <unistd.h>
20#endif
21
22#include <algorithm>
23#include <chrono>
24#include <cmath>
25#include <cstring>
26#include <ctime>
27#include <condition_variable>
28#include <deque>
29#include <fstream>
30#include <iomanip>
31#include <iostream>
32#include <mutex>
33#include <random>
34#include <sstream>
35#include <string>
36#include <thread>
37#include <utility>
38#include <vector>
39
40namespace stdex {
41
42static inline size_t _htons(const unsigned char* srcFirst, const unsigned char* srcLast, unsigned char* dst)
43{
44 size_t result = 0;
45 size_t packet16count = (srcLast-srcFirst)/sizeof(uint16_t);
46 size_t packet8count = (srcLast-srcFirst)%sizeof(uint16_t);
47 const uint16_t* reader16 = reinterpret_cast<const uint16_t*>(srcFirst);
48 uint16_t* writer16 = reinterpret_cast<uint16_t*>(dst);
49 while(packet16count--)
50 *writer16++ = htons(*reader16++);
51 if (packet8count)
52 memcpy(writer16, reader16, packet8count);
53 result = (srcLast-srcFirst);
54 return result;
55}
56//end _htons()
57
58}//end namespace stdex
59
60class Bitmap
61{
62 public:
63 Bitmap(int width = 0, int height=0, int stride=0)
64 :width(std::max(0, width)),height(std::max(0, height)),stride(!stride ? 12*((width+11)/12) : stride) {
65 this->data.resize(this->height*this->stride);
66 if (!this->data.empty())
67 memset(&this->data[0], 0, this->data.size()*sizeof(unsigned char));
68 }
69 Bitmap(const Bitmap& other)
70 :width(other.width),height(other.height),stride(other.stride),data(other.data) {
71 }
72 Bitmap(Bitmap&& other)
73 :width(other.width),height(other.height),stride(other.stride) {
74 other.width = 0;
75 other.height = 0;
76 other.stride = 0;
77 this->data = std::move(other.data);
78 }
79 public:
80 Bitmap& operator=(const Bitmap& other) {
81 this->width = other.width;
82 this->height = other.height;
83 this->stride = other.stride;
84 this->data = other.data;
85 return *this;
86 }//end operator=()
87 public:
88 bool empty(void) const {return this->data.empty();}
89 int getWidth(void) const {return this->width;}
90 int getHeight(void) const {return this->height;}
91 int getStride(void) const {return this->stride;}
92 const std::vector<unsigned char>& getData(void) const {return this->data;}
93 public:
94 void resize(int aWidth = 0, int aHeight=0, int aStride=0)
95 {
96 this->width = std::max(0, aWidth);
97 this->height = std::max(0, aHeight);
98 this->stride = std::max(0, !aStride ? 12*((this->width+11)/12) : aStride);
99 this->data.resize(this->height*this->stride);
100 if (!this->data.empty())
101 memset(&this->data[0], 0, this->data.size()*sizeof(unsigned char));
102 }//end resiz()
103 private:
104 int width;
105 int height;
106 int stride;
107 std::vector<unsigned char> data;
108};
109//end class Bitmap
110
111static volatile bool threadsShouldRun = true;
112
113static std::mutex bitmapsQueueMutex;
114static std::condition_variable bitmapsQueueSemaphore;
115static std::deque<std::pair<Bitmap, std::chrono::system_clock::duration> > bitmapsQueue;
116
117typedef enum {PIXEL_FORMAT_UNDEFINED, PIXEL_FORMAT_RGB888, PIXEL_FORMAT_YCrCb422_8, PIXEL_FORMAT_YCrCb422_10, PIXEL_FORMAT_YCrCb422_12, PIXEL_FORMAT_YCrCb422_14, PIXEL_FORMAT_YCrCb422_16} pixelFormat_t;
118
119void bitmap_draw(Bitmap& bitmap, const std::pair<int, int>& squarePosition, int squareSize)
120{
121 if (!bitmap.empty())
122 {
123 auto now = std::chrono::system_clock::now();
124 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
125 auto shift = (ms%10000)/10000.;
126 const std::vector<unsigned char>& data = bitmap.getData();
127 unsigned char* ptr = const_cast<unsigned char*>(&data[0]);
128 for(int row = 0 ; row < bitmap.getHeight() ; ++row)
129 {
130 unsigned char* pRow = ptr+row*bitmap.getStride();
131 unsigned char* pRowEnd = pRow+bitmap.getStride();
132 memset(pRow, static_cast<unsigned char>(196*std::abs(sin(2*M_PI*row/bitmap.getHeight()-shift*2*M_PI))), pRowEnd-pRow);
133 }//end for each row
134 for(int row = squarePosition.second ; row < std::min(squarePosition.second+squareSize, bitmap.getHeight()) ; ++row)
135 {
136 unsigned char* pRow = ptr+row*bitmap.getStride();
137 unsigned char* pRowEnd = pRow+bitmap.getStride();
138 unsigned char* first = std::min(pRowEnd, pRow+squarePosition.first);
139 unsigned char* last = std::min(pRowEnd, first+squareSize);
140 memset(first, 0xFF, (last-first)*sizeof(unsigned char));
141 }//end for each row
142 }//end if (!bitmap.empty())
143}
144//end bitmap_draw()
145
146void bitmap_generation(double fps, int bitmap_width, int bitmap_height)
147{
148 const size_t bitmapsQueueCapacity = 100;
149 const unsigned int delayMs = static_cast<unsigned int>(std::round(1000./fps));
150 int squareSize = 20;
151 std::pair<int, int> step(1, 1);
152 std::pair<int, int> squarePosition(1, 1);
153
154 auto timestampTimeReference = std::chrono::system_clock::now();
155 auto fpsTimeReference = std::chrono::system_clock::now();
156 auto nextEmissionDate = std::chrono::system_clock::now();
157 size_t bitmapEmittedCount = 0;
158
159 Bitmap bitmap(bitmap_width, bitmap_height);
160 while(threadsShouldRun)
161 {
162 bitmap.resize(bitmap_width, bitmap_height);
163 bitmap_draw(bitmap, squarePosition, squareSize);
164 std::this_thread::sleep_until(nextEmissionDate);
165 auto now = std::chrono::system_clock::now();
166
167 {
168 std::unique_lock<std::mutex> bitmapsQueueLock(bitmapsQueueMutex);
169 if (bitmapsQueue.size() < bitmapsQueueCapacity)
170 {
171 auto duration = now-timestampTimeReference;
172 bitmapsQueue.emplace_back(std::make_pair(std::move(bitmap), duration));
173 bitmapsQueueSemaphore.notify_all();
174 ++bitmapEmittedCount;
175 }//end if (bitmapsQueue.size() < bitmapsQueueCapacity)
176 }
177
178 if (!(bitmapEmittedCount%100))
179 {
180 printf("<~%.2ffps>", 1000.*bitmapEmittedCount/std::chrono::duration_cast<std::chrono::milliseconds>(now-fpsTimeReference).count());
181 fflush(stdout);
182 fpsTimeReference = now;
183 bitmapEmittedCount = 0;
184 }//end if (!(bitmapEmittedCount%100))
185
186 if (((squarePosition.first+step.first)<0) || ((squarePosition.first+step.first)>=(bitmap_width-squareSize)))
187 step.first = -step.first;
188 if (((squarePosition.second+step.second)<0) || ((squarePosition.second+step.second)>=(bitmap_height-squareSize)))
189 step.second = -step.second;
190 squarePosition.first += step.first;
191 squarePosition.second += step.second;
192
193 nextEmissionDate += std::chrono::milliseconds(delayMs);
194 }//end while(threadsShouldRun)
195}
196//end bitmap_generation()
197
198void bitmap_emit(const std::pair<Bitmap, std::chrono::system_clock::duration>& bitmapAndTime, const pixelFormat_t outPixelFormat,
199 const unsigned int ssrc, const int dynPt, unsigned int& rtpSequenceNumber,
200 int socket, const struct sockaddr_in* address, const unsigned int mtu,
201 std::vector<unsigned char>& workBuffer)
202{
203 #pragma pack(push, 1)
204 typedef struct {
205 uint8_t cc:4;
206 uint8_t padding:1;
207 uint8_t extension:1;
208 uint8_t version:2;
209
210 uint8_t pt:7;
211 uint8_t marker:1;
212
213 uint16_t sequenceNumber:16;
214
215 uint32_t timestamp:32;
216
217 uint32_t ssrc:32;
218
219 uint16_t extendedSequenceNumber:16;
220 } rtp_header_t;
221 typedef struct {
222 uint16_t length;
223
224 uint16_t lineNo:15;
225 uint16_t F:1;
226
227 uint16_t offset:15;
228 uint16_t C:1;
229 } line_header_t;
230 #pragma pack(pop)
231
232 const size_t validMtu = !mtu ? 1500 : mtu;
233 const size_t ipv4HeaderMinSize = 20;
234 const size_t ipv6HeaderMinSize = 48;
235 const size_t ipHeaderMinSize = !address ? 0 :
236 (address->sin_family == AF_INET) ? ipv4HeaderMinSize :
237 (address->sin_family == AF_INET6) ? ipv6HeaderMinSize :
238 0;
239 const size_t udpHeaderSize = 8;
240 const size_t maximumUDPPayload = std::max(validMtu, (ipHeaderMinSize+udpHeaderSize))-(ipHeaderMinSize+udpHeaderSize);
241
242 const size_t pgroup =
243 (outPixelFormat == PIXEL_FORMAT_RGB888) ? 3 :
244 (outPixelFormat == PIXEL_FORMAT_YCrCb422_8) ? 4 :
245 (outPixelFormat == PIXEL_FORMAT_YCrCb422_10) ? 5 :
246 (outPixelFormat == PIXEL_FORMAT_YCrCb422_12) ? 6 :
247 (outPixelFormat == PIXEL_FORMAT_YCrCb422_14) ? 7 :
248 (outPixelFormat == PIXEL_FORMAT_YCrCb422_16) ? 8 :
249 0;
250 const size_t rtp_header_size = sizeof(rtp_header_t);
251 const size_t line_header_size = sizeof(line_header_t);
252 const size_t min_line_size = line_header_size + pgroup;
253 const size_t payload = maximumUDPPayload-rtp_header_size;
254
255 const Bitmap& bitmap = bitmapAndTime.first;
256 const std::chrono::system_clock::duration& time = bitmapAndTime.second;
257 if (!bitmap.empty())
258 {
259 const std::vector<unsigned char>& bitmapData = bitmap.getData();
260 const unsigned char* pixelData = &bitmapData[0];
261
262 rtp_header_t rtpHeader = {0};
263 rtpHeader.version = 2;
264 rtpHeader.padding = 0;
265 rtpHeader.extension = 0;
266 rtpHeader.cc = 0;
267 rtpHeader.marker = 0;
268 rtpHeader.pt = dynPt;
269 auto timeStampMus = std::chrono::duration_cast<std::chrono::milliseconds>(time);
270 uint32_t rtpTimestamp = static_cast<uint32_t>(90000*timeStampMus.count()/1000);
271 rtpHeader.timestamp = htonl(rtpTimestamp);
272 rtpHeader.ssrc = htonl(ssrc);
273
274 std::vector<unsigned char>& buffer = workBuffer;
275 buffer.resize(rtp_header_size+payload);
276 std::vector<std::pair<const unsigned char*, const unsigned char*> > fragmentsToWrite;
277 unsigned char* bufferStart = &buffer[0];
278 unsigned char* bufferEnd = bufferStart+buffer.size();
279 int currentRow = 0;
280 const unsigned char* pRowSrc = pixelData+currentRow*bitmap.getStride();
281 const unsigned char* pRowSrcEnd = pRowSrc+bitmap.getWidth();
282 const unsigned char* pRowReader = pRowSrc;
283 while(currentRow < bitmap.getHeight())
284 {
285 unsigned char* writer = bufferStart+rtp_header_size;
286 fragmentsToWrite.resize(0);
287 size_t remainingRoom = bufferEnd-writer;
288 while(remainingRoom >= min_line_size)
289 {
290 size_t remainingRoomForPixels = (remainingRoom-line_header_size);
291 size_t maxEmittablePixelsCount =
292 (outPixelFormat == PIXEL_FORMAT_RGB888) ? 1*(remainingRoomForPixels/pgroup) :
293 (outPixelFormat == PIXEL_FORMAT_YCrCb422_8) ? 2*(remainingRoomForPixels/pgroup) :
294 (outPixelFormat == PIXEL_FORMAT_YCrCb422_10) ? 2*(remainingRoomForPixels/pgroup) :
295 (outPixelFormat == PIXEL_FORMAT_YCrCb422_12) ? 2*(remainingRoomForPixels/pgroup) :
296 (outPixelFormat == PIXEL_FORMAT_YCrCb422_14) ? 2*(remainingRoomForPixels/pgroup) :
297 (outPixelFormat == PIXEL_FORMAT_YCrCb422_16) ? 2*(remainingRoomForPixels/pgroup) :
298 0;
299 size_t remainingPixelsToEmitFromCurrentRow = (pRowSrcEnd-pRowReader);
300 size_t pixelsToEmitOnCurrentFragment = std::min(maxEmittablePixelsCount, remainingPixelsToEmitFromCurrentRow);
301 size_t bytesToEmitOnCurrentFragment =
302 (outPixelFormat == PIXEL_FORMAT_RGB888) ? (((pixelsToEmitOnCurrentFragment+0)/1)*pgroup) :
303 (outPixelFormat == PIXEL_FORMAT_YCrCb422_8) ? (((pixelsToEmitOnCurrentFragment+1)/2)*pgroup) :
304 (outPixelFormat == PIXEL_FORMAT_YCrCb422_10) ? (((pixelsToEmitOnCurrentFragment+1)/2)*pgroup) :
305 (outPixelFormat == PIXEL_FORMAT_YCrCb422_12) ? (((pixelsToEmitOnCurrentFragment+1)/2)*pgroup) :
306 (outPixelFormat == PIXEL_FORMAT_YCrCb422_14) ? (((pixelsToEmitOnCurrentFragment+1)/2)*pgroup) :
307 (outPixelFormat == PIXEL_FORMAT_YCrCb422_16) ? (((pixelsToEmitOnCurrentFragment+1)/2)*pgroup) :
308 0;
309 bool isLastFragmentInCurrentPacket = (line_header_size+bytesToEmitOnCurrentFragment+min_line_size > remainingRoom);
310 line_header_t lineHeader = {0};
311 lineHeader.length = static_cast<uint16_t>(bytesToEmitOnCurrentFragment);
312 lineHeader.F = 0;
313 lineHeader.lineNo = static_cast<uint16_t>(currentRow);
314 lineHeader.C = isLastFragmentInCurrentPacket ? 0 : 1;
315 lineHeader.offset = static_cast<uint16_t>(pRowReader-pRowSrc);
316 writer += stdex::_htons(reinterpret_cast<const unsigned char*>(&lineHeader), reinterpret_cast<const unsigned char*>(&lineHeader)+line_header_size, writer);
317 remainingRoom -= line_header_size+bytesToEmitOnCurrentFragment;
318 const unsigned char* pRowReaderNext = std::min(pRowSrcEnd, pRowReader+pixelsToEmitOnCurrentFragment);
319 fragmentsToWrite.push_back(std::make_pair(pRowReader, pRowReaderNext));
320 pRowReader = pRowReaderNext;
321 bool isRowCompleted = (pRowReader >= pRowSrcEnd);
322 if (isRowCompleted)
323 {
324 ++currentRow;
325 if (currentRow < bitmap.getHeight())
326 {
327 pRowSrc = pixelData+currentRow*bitmap.getStride();
328 pRowSrcEnd = pRowSrc+bitmap.getWidth();
329 pRowReader = pRowSrc;
330 }//end if (currentRow < bitmapHeight)
331 }//end if (isRowCompleted)
332 }//end while(remainingRoom >= min_line_size)
333 rtpHeader.marker = (currentRow < bitmap.getHeight()) ? 0 : 1;
334 if (outPixelFormat == PIXEL_FORMAT_RGB888)
335 {
336 for(auto lineFragment : fragmentsToWrite)
337 {
338 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
339 {
340 uint8_t pixel = static_cast<uint8_t>((pPixel < lineFragment.second) ? *pPixel++ : 0);
341 uint8_t R = pixel;
342 uint8_t G = pixel;
343 uint8_t B = pixel;
344 *writer++ = R;
345 *writer++ = G;
346 *writer++ = B;
347 }//end for each pixel
348 }//end for each fragment
349 }//end if (outPixelFormat == PIXEL_FORMAT_RGB888)
350 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_8)
351 {
352 for(auto lineFragment : fragmentsToWrite)
353 {
354 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
355 {
356 uint8_t Cr = static_cast<uint8_t>((1<<8)/2);
357 uint8_t Cb = static_cast<uint8_t>((1<<8)/2);
358 uint8_t Y0 = static_cast<uint8_t>((pPixel < lineFragment.second) ? *pPixel++ : 0);
359 uint8_t Y1 = static_cast<uint8_t>((pPixel < lineFragment.second) ? *pPixel++ : 0);
360 *writer++ = Cr;
361 *writer++ = Y0;
362 *writer++ = Cb;
363 *writer++ = Y1;
364 }//end for each pixel
365 }//end for each fragment
366 }//end if (outPixelFormat == PIXEL_FORMAT_YCrCb422_8)
367 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_10)
368 {
369 for(auto lineFragment : fragmentsToWrite)
370 {
371 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
372 {
373 uint16_t Cr = static_cast<uint16_t>((1<<10)/2);
374 uint16_t Cb = static_cast<uint16_t>((1<<10)/2);
375 uint16_t Y0 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 2;
376 uint16_t Y1 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 2;
377 *writer++ = 0 | ((Cr >> 2) & 0xFF);// Cr high (8)
378 *writer++ = ((Cr & 0x03) << 6) | ((Y0 >> 4) & 0x3F);//Cr low (2) | Y0 high (6)
379 *writer++ = ((Y0 & 0x0F) << 4) | ((Cb >> 6) & 0x0F);//Y0 low (4) | Cb high (4)
380 *writer++ = ((Cb & 0x3F) << 2) | ((Y1 >> 8) & 0x03);//Cb low (6) | Y1 high (2)
381 *writer++ = ((Y1 & 0xFF) << 0) | 0;//Y1 low (8)
382 }//end for each pixel
383 }//end for each fragment
384 }//end if (outPixelFormat == PIXEL_FORMAT_YCrCb422_10)
385 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_12)
386 {
387 for(auto lineFragment : fragmentsToWrite)
388 {
389 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
390 {
391 uint16_t Cr = static_cast<uint16_t>((1<<12)/2);
392 uint16_t Cb = static_cast<uint16_t>((1<<12)/2);
393 uint16_t Y0 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 4;
394 uint16_t Y1 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 4;
395 *writer++ = 0 | ((Cr >> 4) & 0xFF);// | Cr high (8)
396 *writer++ = ((Cr & 0x0F) << 4) | ((Y0 >> 8) & 0x0F);//Cr low (4) | Y0 high (4)
397 *writer++ = ((Y0 & 0xFF) << 0) | 0;//Y0 low (8) |
398 *writer++ = 0 | ((Cb >> 4) & 0xFF);// | Cb high (8)
399 *writer++ = ((Cb & 0x0F) << 4) | ((Y1 >> 8) & 0x0F);//Cb low (4) | Y1 high (4)
400 *writer++ = ((Y1 & 0xFF) << 0) | 0;//Y1 low (8) |
401 }//end for each pixel
402 }//end for each fragment
403 }//end if (outPixelFormat == PIXEL_FORMAT_YCrCb422_12)
404 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_14)
405 {
406 for(auto lineFragment : fragmentsToWrite)
407 {
408 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
409 {
410 uint16_t Cr = static_cast<uint16_t>((1<<14)/2);
411 uint16_t Cb = static_cast<uint16_t>((1<<14)/2);
412 uint16_t Y0 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 6;
413 uint16_t Y1 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 6;
414 *writer++ = 0 | ((Cr >> 6) & 0xFF);// | Cr high (8)
415 *writer++ = ((Cr & 0x3F) << 2) | ((Y0 >> 12) & 0x03);//Cr low (6) | Y0 high (2)
416 *writer++ = ((Y0 >> 4) & 0xFF) | 0;//Y0 mid (8) |
417 *writer++ = ((Y0 & 0x0F) << 4) | ((Cb >> 10) & 0x0F);//Y0 low (4) | Cb high (4)
418 *writer++ = ((Cb >> 2) & 0xFF) | 0;//Cb mid (8) |
419 *writer++ = ((Cb & 0x03) << 6) | ((Y0 >> 8) & 0x3F);//Cb low (2) | Y1 mid (6)
420 *writer++ = ((Y1 & 0xFF) << 0) | 0;//Y1 low (8) |
421 }//end for each pixel
422 }//end for each fragment
423 }//end if (outPixelFormat == PIXEL_FORMAT_YCrCb422_14)
424 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_16)
425 {
426 uint16_t* writer16 = reinterpret_cast<uint16_t*>(writer);
427 for(auto lineFragment : fragmentsToWrite)
428 {
429 for(const unsigned char* pPixel = lineFragment.first ; pPixel < lineFragment.second ; )
430 {
431 uint16_t Cr = static_cast<uint16_t>((1<<16)/2);
432 uint16_t Cb = static_cast<uint16_t>((1<<16)/2);
433 uint16_t Y0 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 8;
434 uint16_t Y1 = static_cast<uint16_t>((pPixel < lineFragment.second) ? *pPixel++ : 0) << 8;
435 *writer16++ = htons(Cr);
436 *writer16++ = htons(Y0);
437 *writer16++ = htons(Cb);
438 *writer16++ = htons(Y1);
439 }//end for each pixel
440 }//end for each fragment
441 writer = reinterpret_cast<unsigned char*>(writer16);
442 }//end if (outPixelFormat == PIXEL_FORMAT_YCrCb422_16)
443 if (rtpHeader.marker)
444 std::cout << '.' << std::flush;
445 unsigned int currentRtpSequenceNumber = rtpSequenceNumber++;
446 rtpHeader.sequenceNumber = htons(static_cast<uint16_t>(currentRtpSequenceNumber) & 0xFFFF);
447 rtpHeader.extendedSequenceNumber = htons(static_cast<uint16_t>(currentRtpSequenceNumber >> 16) & 0xFFFF);
448 memcpy(&buffer[0], &rtpHeader, rtp_header_size);
449 if ((socket >= 0) && address)
450 sendto(socket, reinterpret_cast<const char*>(&buffer[0]), static_cast<int>(buffer.size()), 0, reinterpret_cast<const sockaddr*>(address), sizeof(*address));
451 }//end while(currentRow < bitmapHeight)
452 }//end if (!bitmap.empty())
453}
454//end bitmap_emit()
455
456void bitmap_emission(const pixelFormat_t outPixelFormat, const std::string& ipString, const uint16_t server_port, const unsigned int mtu, const unsigned int ssrc, const int dynPt)
457{
458 int error = 0;
459 unsigned int rtpSequenceNumber = 0;
460
461 int server_socket = (int)socket(AF_INET, SOCK_DGRAM, (int)IPPROTO_UDP);
462
463 char broadcast = 1;
464 error = setsockopt(server_socket, SOL_SOCKET, SO_BROADCAST, reinterpret_cast<const char*>(&broadcast), sizeof(broadcast));
465
466 struct sockaddr_in broadcast_addr = {0};
467 broadcast_addr.sin_family = AF_INET;
468 broadcast_addr.sin_port = htons(server_port);
469 inet_pton(AF_INET, ipString.c_str(), &broadcast_addr.sin_addr);
470 *reinterpret_cast<uint32_t*>(&broadcast_addr.sin_addr) |= htonl(0x000000FF);//make broadcast address
471 char addressBuffer[INET_ADDRSTRLEN] = {0};
472 inet_ntop(AF_INET, &broadcast_addr.sin_addr, addressBuffer, sizeof(addressBuffer));
473 std::cout << "will broadcast to " << addressBuffer << ':' << server_port << std::endl;
474
475 std::vector<unsigned char> workBuffer;
476
477 while(threadsShouldRun)
478 {
479 std::unique_lock<std::mutex> bitmapsQueueLock(bitmapsQueueMutex);
480 std::cv_status status = bitmapsQueueSemaphore.wait_for(bitmapsQueueLock, std::chrono::milliseconds(1000));
481 while(!bitmapsQueue.empty())
482 {
483 auto front = std::move(bitmapsQueue.front());
484 bitmap_emit(front, outPixelFormat, ssrc, dynPt, rtpSequenceNumber, server_socket, &broadcast_addr, mtu, workBuffer);
485 bitmapsQueue.pop_front();
486 }//end if (!bitmapsQueue.empty())
487 }//end while(threadsShouldRun)
488}
489//end bitmap_emission()
490
491void test_listen_udp(const uint16_t server_port)
492{
493 std::this_thread::sleep_for(std::chrono::milliseconds(1000));
494
495 int error = 0;
496
497 int listeningSocket = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
498 struct sockaddr_in sockaddr = {0};
499 sockaddr.sin_family = AF_INET;
500 sockaddr.sin_port = htons(server_port);
501 sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
502
503 struct timeval timeV = {0};
504 timeV.tv_sec = 2;
505 timeV.tv_usec = 0;
506
507 error = setsockopt(listeningSocket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&timeV), sizeof(timeV));
508
509 error = bind(listeningSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr));
510 std::vector<unsigned char> buffer(1U*4*1024*1024);
511 while(true)
512 {
513 memset(&buffer[0], 0, buffer.size()*sizeof(unsigned char));
514 struct sockaddr_in receiveSockaddr = {0};
515 socklen_t receiveSockaddrLen = sizeof(receiveSockaddr);
516 int numbytes = recvfrom(listeningSocket, reinterpret_cast<char*>(&buffer[0]), static_cast<int>(buffer.size()*sizeof(unsigned char)), 0, (struct sockaddr*)&receiveSockaddr, &receiveSockaddrLen);
517 std::cout << '<' << numbytes << '>';
518 }
519}
520//end test_listen_udp()
521
522int main(void)
523{
524 const double fps_generation = 25;
525
526 const int bitmap_width = 640;
527 const int bitmap_height = 480;
528 const pixelFormat_t outPixelFormat = PIXEL_FORMAT_RGB888;//PIXEL_FORMAT_YCrCb422_10;//PIXEL_FORMAT_YCrCb422_16;
529
530 const uint16_t server_port = 4567;
531
532 std::random_device randomDevice;
533 std::uniform_int_distribution<unsigned int> distribution;
534 const unsigned int ssrc = distribution(randomDevice);
535
536 #if defined(WIN32)
537 WSADATA wsa = {0};
538 WSAStartup(MAKEWORD(2,2), &wsa);
539 #endif
540
541 std::string preferredIpString = "127.0.0.1";
542 unsigned int mtu = 0;
543
544 #if defined(WIN32)
545 std::vector<unsigned char> buffer(1U*4*1024);
546 ULONG actualSize = static_cast<ULONG>(buffer.size());
547 PMIB_IPADDRTABLE addrTable = reinterpret_cast<PMIB_IPADDRTABLE>(&buffer[0]);
548 GetIpAddrTable(addrTable, &actualSize, 0);
549 int ifIpv4Index = 0;
550 if (actualSize)
551 for(DWORD i=0 ; i < addrTable->dwNumEntries ; ++i)
552 {
553 const MIB_IPADDRROW& entry = addrTable->table[i];
554 IN_ADDR ipAddress = {0};
555 ipAddress.S_un.S_addr = entry.dwAddr;
556 char addressBuffer[INET_ADDRSTRLEN] = {0};
557 inet_ntop(AF_INET, &ipAddress, addressBuffer, sizeof(addressBuffer));
558 std::string candidate(addressBuffer, strlen(addressBuffer));
559 if (candidate != preferredIpString)
560 {
561 preferredIpString = candidate;
562 ifIpv4Index = i;
563 break;
564 }
565 }
566 PIP_ADAPTER_ADDRESSES adapterAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(&buffer[0]);
567 actualSize = static_cast<ULONG>(buffer.size());
568 GetAdaptersAddresses(AF_INET, 0, 0, adapterAddresses, &actualSize);
569 PIP_ADAPTER_ADDRESSES current = adapterAddresses;
570 while(ifIpv4Index && current)
571 {
572 current = current->Next;
573 --ifIpv4Index;
574 }
575 mtu = !current ? 0 : current->Mtu;
576 #else
577 struct ifaddrs* ifAddresses = 0;
578 getifaddrs(&ifAddresses);
579 for (struct ifaddrs* ifa = ifAddresses; ifa != 0; ifa = ifa->ifa_next)
580 {
581 if (!ifa->ifa_addr) {
582 }
583 else if (ifa->ifa_addr->sa_family == AF_INET)
584 {
585 void* tmpAddrPtr = &((struct sockaddr_in*)ifa->ifa_addr)->sin_addr;
586 char addressBuffer[INET_ADDRSTRLEN] = {0};
587 inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
588 std::string candidate(addressBuffer, strlen(addressBuffer));
589 if (candidate != preferredIpString)
590 {
591 preferredIpString = candidate;
592 int dummy_socket = (int)socket(AF_INET, SOCK_DGRAM, (int)IPPROTO_UDP);
593 struct ifreq ifr = {0};
594 strcpy(ifr.ifr_name, ifa->ifa_name);
595 int error = ioctl(dummy_socket, SIOCGIFMTU, &ifr);
596 mtu = ifr.ifr_mtu;
597 if (dummy_socket >= 0)
598 close(dummy_socket);
599 break;
600 }//end if (candidate != preferredIpString)
601 }
602 }//end for each ifa
603 if (ifAddresses)
604 freeifaddrs(ifAddresses);
605 #endif
606
607 std::cout << "Detected MTU : " << mtu << std::endl;
608 std::cout << "here is a SDP description:" << std::endl;
609 std::cout << "=================================" << std::endl;
610 const int ttl = 127;
611 const int dynPt = 112;
612 std::stringstream ss;
613 ss << "SDP:" << std::endl;
614 ss << "v=0" << std::endl;
615 ss << "o=" << "toto" << ' ' << ssrc << ' ' << ssrc << ' ' << preferredIpString << std::endl;
616 ss << "s=" << ssrc << std::endl;
617 ss << "c=" << "IN IP4" << ' ' << preferredIpString << '/' << ttl << std::endl;
618 ss << "m=" << "video" << ' ' << server_port << ' ' << "RTP/AVP" << ' ' << dynPt << std::endl;
619 ss << "a=" << "rtpmap:" << dynPt << ' ' << "raw/90000" << std::endl;
620 if (outPixelFormat == PIXEL_FORMAT_RGB888)
621 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=RGB; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=8; colorimetry=BT.709-2" << std::endl;
622 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_8)
623 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=YCbCr-4:2:2; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=8; colorimetry=BT.709-2; chroma-position=1" << std::endl;
624 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_10)
625 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=YCbCr-4:2:2; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=10; colorimetry=BT.709-2; chroma-position=1" << std::endl;
626 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_12)
627 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=YCbCr-4:2:2; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=12; colorimetry=BT.709-2; chroma-position=1" << std::endl;
628 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_14)
629 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=YCbCr-4:2:2; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=14; colorimetry=BT.709-2; chroma-position=1" << std::endl;
630 else if (outPixelFormat == PIXEL_FORMAT_YCrCb422_16)
631 ss << "a=" << "fmtp:" << dynPt << ' ' << "sampling=YCbCr-4:2:2; width=" << bitmap_width << "; height=" << bitmap_height << "; depth=16; colorimetry=BT.709-2; chroma-position=1" << std::endl;
632 ss << "a=" << "framerate:" << fps_generation << std::endl;
633 std::string sdpString = ss.str();
634 std::cout << sdpString << std::endl;
635 std::cout << "=================================" << std::endl;
636 std::ofstream fo("rtpgenerator.sdp");
637 fo << sdpString << std::endl;
638 fo.close();
639
640
641 std::thread bitmap_generator_thread(bitmap_generation, fps_generation, bitmap_width, bitmap_height);
642 std::thread bitmap_emission_thread(bitmap_emission, outPixelFormat, preferredIpString, server_port, mtu, ssrc, dynPt);
643 //std::thread test_udp_listen_thread(test_listen_udp, server_port);
644
645 std::cin.get();
646 threadsShouldRun = false;
647
648 bitmap_generator_thread.join();
649 bitmap_emission_thread.join();
650 //test_udp_listen_thread.join();
651
652 #if defined(WIN32)
653 WSACleanup();
654 #endif
655
656 return 0;
657}
658