00001
00002 #include "ffmpegServer.h"
00003
00004
00005 #include "epicsExport.h"
00006 #include "iocsh.h"
00007 #include <epicsExit.h>
00008 #include <epicsThread.h>
00009 #include <time.h>
00010 #include <math.h>
00011
00012
00013 #ifdef _MSC_VER
00014
00015 int pthread_cond_init (pthread_cond_t *cv, const pthread_condattr_t *) {
00016 cv->semaphore = CreateEvent (NULL, FALSE, FALSE, NULL);
00017 return 0;
00018 }
00020 int pthread_cond_wait (pthread_cond_t *cv, pthread_mutex_t *external_mutex) {
00021 pthread_mutex_unlock(external_mutex);
00023 WaitForSingleObject (cv->semaphore, INFINITE);
00024 pthread_mutex_lock(external_mutex);
00025 return 0;
00026 }
00028 int pthread_cond_signal (pthread_cond_t *cv) {
00029 SetEvent (cv->semaphore);
00030 return 0;
00031 }
00032 #endif
00033
00034 static const char *driverName = "ffmpegServer";
00035
00037 void dorequest(int sid) {
00038 char *portName;
00039 int len;
00040 char *ext;
00041
00042 if (read_header(sid)<0) {
00043 closeconnect(sid, 1);
00044 return;
00045 }
00046 logaccess(2, "%s - HTTP Request: %s %s", conn[sid].dat->in_RemoteAddr,
00047 conn[sid].dat->in_RequestMethod, conn[sid].dat->in_RequestURI);
00048 snprintf(conn[sid].dat->out_ContentType,
00049 sizeof(conn[sid].dat->out_ContentType)-1, "text/html");
00050
00051
00052 ext = strrchr(conn[sid].dat->in_RequestURI+1, '.');
00053
00054 if (ext != NULL) {
00055 len = ext - conn[sid].dat->in_RequestURI - 1;
00056 portName = (char *)calloc(sizeof(char), 256);
00057 strncpy(portName, conn[sid].dat->in_RequestURI+1, len);
00058 ext++;
00059 for (int i=0; i<nstreams; i++) {
00060 if (strcmp(portName, streams[i]->portName) == 0) {
00061 if (strcmp(ext, "index") == 0) {
00062 streams[i]->send_snapshot(sid, 1);
00063 free(portName);
00064 return;
00065 }
00066 if (strcmp(ext, "jpg") == 0 || strcmp(ext, "jpeg") == 0) {
00067 streams[i]->send_snapshot(sid, 0);
00068 free(portName);
00069 return;
00070 }
00071 if (strcmp(ext, "mjpg") == 0 || strcmp(ext, "mjpeg") == 0) {
00072 streams[i]->send_stream(sid);
00073 free(portName);
00074 return;
00075 }
00076
00077 }
00078 }
00079 }
00080
00081
00082 send_header(sid, 0, 200, "OK", "1", "text/html", -1, -1);
00083 prints("\n\
00084 <HTML> \n\
00085 <style type=\"text/css\"> \n\
00086 BODY { \n\
00087 background-color: #f2f2f6; \n\
00088 font-family: arial, sans-serif; \n\
00089 } \n\
00090 H1 { \n\
00091 font-size: 24px; \n\
00092 color: #000000; \n\
00093 font-weight: bold; \n\
00094 text-align: center; \n\
00095 } \n\
00096 H2 { \n\
00097 font-size: 18px; \n\
00098 color: #1b2a60; \n\
00099 font-weight: bold; \n\
00100 text-align: center; \n\
00101 } \n\
00102 A:link { \n\
00103 text-decoration: none; color:#3b4aa0; \n\
00104 } \n\
00105 A:visited { \n\
00106 text-decoration: none; color:#3b4aa0; \n\
00107 } \n\
00108 A:active { \n\
00109 text-decoration: none; color:#3b4aa0; \n\
00110 } \n\
00111 A:hover { \n\
00112 text-decoration: underline; color:#3b4aff; \n\
00113 } \n\
00114 td { \n\
00115 background-color: #e0e0ee; \n\
00116 border-style: outset; \n\
00117 border-color: #e0e0ee; \n\
00118 border-width: 1px; \n\
00119 padding: 10px; \n\
00120 text-align: center; \n\
00121 } \n\
00122 p { \n\
00123 text-align: center; \n\
00124 } \n\
00125 </style> \n\
00126 <HEAD> \n\
00127 <TITLE>ffmpegServer Content Listing</TITLE> \n\
00128 </HEAD> \n\
00129 <BODY> \n\
00130 <CENTER> \n\
00131 <H1>ffmpegServer Content Listing</H1> \n\
00132 <TABLE cellspacing=\"15\"> \n\
00133 <TR> \n\
00134 ");
00135
00136 for (int i=0; i<nstreams; i++) {
00137 prints("<TD>\n");
00138 prints("<H2>%s</H2>\n", streams[i]->portName);
00139 prints("<img src=\"%s.index\" height=\"192\" title=\"Static JPEG\" alt=\"<No image yet>\"/>\n", streams[i]->portName);
00140 prints("<p><a href=\"%s.jpg\">Link to Static JPEG</a></p>\n", streams[i]->portName);
00141 prints("<p><a href=\"%s.mjpg\">Link to MJPEG Stream</a></p>\n", streams[i]->portName);
00142 prints("</TD>\n");
00143 if (i % 3 == 2) {
00144 prints(" </TR>\n <TR>\n");
00145 }
00146 }
00147 prints("\n\
00148 </TR> \n\
00149 </TABLE> \n\
00150 </CENTER> \n\
00151 </BODY> \n\
00152 </HTML> \n\
00153 ");
00154 flushbuffer(sid);
00155 }
00156
00158 int config_read()
00159 {
00160 snprintf(config.server_base_dir, sizeof(config.server_base_dir)-1, "%s", DEFAULT_BASE_DIR);
00161 snprintf(config.server_bin_dir, sizeof(config.server_bin_dir)-1, "%s/bin", config.server_base_dir);
00162 snprintf(config.server_cgi_dir, sizeof(config.server_cgi_dir)-1, "%s/cgi-bin", config.server_base_dir);
00163 snprintf(config.server_etc_dir, sizeof(config.server_etc_dir)-1, "%s/etc", config.server_base_dir);
00164 snprintf(config.server_htdocs_dir, sizeof(config.server_htdocs_dir)-1, "%s/htdocs", config.server_base_dir);
00165 fixslashes(config.server_base_dir);
00166 fixslashes(config.server_bin_dir);
00167 fixslashes(config.server_cgi_dir);
00168 fixslashes(config.server_etc_dir);
00169 fixslashes(config.server_htdocs_dir);
00170 return 0;
00171 }
00172
00173 static int stopping = 0;
00174
00176 void c_shutdown(void *) {
00177 printf("Shutting down http server...");
00178 stopping = 1;
00179 server_shutdown();
00180 sleep(1);
00181 printf("OK\n");
00182 }
00183
00188 void ffmpegServerConfigure(int port) {
00189 int status;
00190 if (port==0) {
00191 port = 8080;
00192 }
00193 streams = (ffmpegStream **) calloc(MAX_FFMPEG_STREAMS, sizeof(ffmpegStream *));
00194 nstreams = 0;
00195 config.server_port = port;
00196 config.server_loglevel=1;
00197 strncpy(config.server_hostname, "any", sizeof(config.server_hostname)-1);
00198 config.server_maxconn=50;
00199 config.server_maxidle=120;
00200 printf("Starting server on port %d...\n", port);
00201 snprintf((char *)program_name, sizeof(program_name)-1, "ffmpegServer");
00202 init();
00203 #ifdef WIN32
00204 if (_beginthread(WSAReaper, 0, NULL)==-1) {
00205 logerror("Winsock reaper thread failed to start");
00206 exit(0);
00207 }
00208 #endif
00209
00210 status = (epicsThreadCreate("httpServer",
00211 epicsThreadPriorityMedium,
00212 epicsThreadGetStackSize(epicsThreadStackMedium),
00213 (EPICSTHREADFUNC)accept_loop,
00214 NULL) == NULL);
00215 if (status) {
00216 printf("%s:ffmpegServerConfigure epicsThreadCreate failure for image task\n",
00217 driverName);
00218 return;
00219 } else printf("OK\n");
00220
00221 epicsAtExit(c_shutdown, NULL);
00222 }
00223
00225 void ffmpegStream::send_snapshot(int sid, int index) {
00226 time_t now=time((time_t*)0);
00227 int size, always_on;
00228 NDArray* pArray;
00229
00230
00231 getIntegerParam(0, ffmpegServerAlwaysOn, &always_on);
00232 pthread_mutex_lock( &this->mutex );
00233 this->nclients++;
00234 if (this->nclients > 1) always_on = 1;
00235 pthread_mutex_unlock(&this->mutex);
00236
00237 if (always_on || index) {
00238 pArray = get_jpeg();
00239 } else {
00240 pArray = wait_for_jpeg(sid);
00241 }
00242
00243 pthread_mutex_lock( &this->mutex );
00244 this->nclients--;
00245 pthread_mutex_unlock(&this->mutex);
00246
00247 if (pArray == NULL) {
00248 printerror(sid, 200, "No Data", "No jpeg available yet");
00249 return;
00250 }
00251
00252 size = pArray->dims[0].size;
00253 conn[sid].dat->out_ContentLength=size;
00254 send_fileheader(sid, 0, 200, "OK", "1", "image/jpeg", size, now);
00255
00256 send(conn[sid].socket, (const char *) pArray->pData, size, 0);
00257 pArray->release();
00258
00259 conn[sid].dat->out_headdone=1;
00260 conn[sid].dat->out_bodydone=1;
00261 conn[sid].dat->out_flushed=1;
00262 conn[sid].dat->out_ReplyData[0]='\0';
00263 flushbuffer(sid);
00264 }
00265
00266 #define MIN(a, b) (((a) < (b)) ? (a) : (b))
00267
00268
00270 int ffmpegStream::send_frame(int sid, NDArray *pArray) {
00271 int ret = 0;
00272
00273
00274 if (pArray) {
00275
00276
00277 prints("Content-Type: image/jpeg\r\n");
00278 prints("Content-Length: %d\r\n\r\n", pArray->dims[0].size);
00279 flushbuffer(sid);
00280
00281
00282 ret = send(conn[sid].socket, (const char *) pArray->pData, pArray->dims[0].size, 0);
00283
00284
00285 prints("\r\n--BOUNDARY\r\n");
00286 flushbuffer(sid);
00287
00288
00289
00290 pArray->release();
00291 }
00292 return ret;
00293 }
00294
00296 NDArray* ffmpegStream::get_jpeg() {
00297 NDArray* pArray;
00298 pthread_mutex_lock(&this->mutex);
00299 pArray = this->jpeg;
00300 if (pArray) pArray->reserve();
00301 pthread_mutex_unlock(&this->mutex);
00302 return pArray;
00303 }
00304
00305
00307 NDArray* ffmpegStream::wait_for_jpeg(int sid) {
00308 NDArray* pArray;
00309 pthread_mutex_lock(&this->mutex);
00310 pthread_cond_wait(&(this->cond[sid]), &this->mutex);
00311 pArray = this->jpeg;
00312 pArray->reserve();
00313 pthread_mutex_unlock(&this->mutex);
00314 return pArray;
00315 }
00316
00318 void ffmpegStream::send_stream(int sid) {
00319 int ret = 0;
00320 int always_on;
00321 NDArray* pArray;
00322 time_t now=time((time_t*)0);
00323
00324 getIntegerParam(0, ffmpegServerAlwaysOn, &always_on);
00325 pthread_mutex_lock( &this->mutex );
00326 this->nclients++;
00327 if (this->nclients > 1) always_on = 1;
00328 pthread_mutex_unlock(&this->mutex);
00329
00330 send_fileheader(sid, 0, 200, "OK", "1", "multipart/x-mixed-replace;boundary=BOUNDARY", -1, now);
00331 prints("--BOUNDARY\r\n");
00332 flushbuffer(sid);
00333
00334 if (always_on) {
00335 pArray = get_jpeg();
00336 ret = send_frame(sid, pArray);
00337 }
00338
00339 while (ret >= 0 && !stopping) {
00340
00341 pArray = wait_for_jpeg(sid);
00342 ret = send_frame(sid, pArray);
00343 }
00344
00345 pthread_mutex_lock( &this->mutex );
00346 this->nclients--;
00347 pthread_mutex_unlock(&this->mutex);
00348 }
00349
00351 void ffmpegStream::allocScArray(size_t size) {
00352 if (this->scArray) {
00353 if (this->scArray->dims[0].size >= size) {
00354
00355 avpicture_fill((AVPicture *)scPicture,(uint8_t *)scArray->pData,c->pix_fmt,c->width,c->height);
00356 return;
00357 } else {
00358
00359 this->scArray->release();
00360 }
00361 }
00362 this->scArray = this->pNDArrayPool->alloc(1, &size, NDInt8, 0, NULL);
00363
00364 avpicture_fill((AVPicture *)scPicture,(uint8_t *)scArray->pData,c->pix_fmt,c->width,c->height);
00365 }
00366
00367
00371 void ffmpegStream::processCallbacks(NDArray *pArray)
00372 {
00373
00374
00375
00376
00377 int quality, clients, false_col, always_on, maxw, maxh;
00378
00379 int width, height;
00380 size_t size;
00381
00382 const char *functionName = "processCallbacks";
00383
00384 int colorMode = NDColorModeMono;
00385 NDAttribute *pAttribute = NULL;
00386
00387
00388 NDPluginDriver::processCallbacks(pArray);
00389
00390
00391 pthread_mutex_lock(&this->mutex);
00392 clients = this->nclients;
00393 pthread_mutex_unlock(&this->mutex);
00394 setIntegerParam(0, ffmpegServerClients, clients);
00395
00396
00397 getIntegerParam(0, ffmpegServerQuality, &quality);
00398 getIntegerParam(0, ffmpegServerFalseCol, &false_col);
00399 getIntegerParam(0, ffmpegServerAlwaysOn, &always_on);
00400 getIntegerParam(0, ffmpegServerMaxW, &maxw);
00401 getIntegerParam(0, ffmpegServerMaxH, &maxh);
00402
00403
00404 if (clients == 0 && always_on == 0) {
00405
00406 return;
00407 }
00408
00409
00410
00411
00412 this->unlock();
00413
00414
00415 pAttribute = pArray->pAttributeList->find("ColorMode");
00416 if (pAttribute) pAttribute->getValue(NDAttrInt32, &colorMode);
00417 if ((pArray->ndims == 2) && (colorMode == NDColorModeMono)) {
00418 width = pArray->dims[0].size;
00419 height = pArray->dims[1].size;
00420 } else if ((pArray->ndims == 3) && (pArray->dims[0].size == 3) && (colorMode == NDColorModeRGB1)) {
00421 width = pArray->dims[1].size;
00422 height = pArray->dims[2].size;
00423 } else {
00424 width = pArray->dims[0].size;
00425 height = pArray->dims[1].size;
00426 }
00427
00428
00429 if (width > maxw || height > maxh) {
00430 double sf = MIN(((double)maxw)/width, ((double)maxh)/height);
00431 width = (int) (sf * width);
00432 height = (int) (sf * height);
00433 }
00434 size = width * height;
00435
00436
00437 if (c == NULL || width != c->width || height != c->height) {
00438
00439 AVRational avr;
00440 avr.num = 1;
00441 avr.den = 25;
00442 if (c != NULL) {
00443
00444 avcodec_close(c);
00445 av_free(c);
00446 }
00447 c = avcodec_alloc_context();
00448
00449 if (width * height < FF_MIN_BUFFER_SIZE) {
00450 double sf = sqrt(1.0 * FF_MIN_BUFFER_SIZE / width / height);
00451 height = (int) (height * sf + 1);
00452 width = (int) (width * sf + 1);
00453 }
00454 c->width = width;
00455 c->height = height;
00456 c->flags = CODEC_FLAG_QSCALE;
00457 c->time_base = avr;
00458 c->pix_fmt = PIX_FMT_YUVJ420P;
00459 if(codec && codec->pix_fmts){
00460 const enum PixelFormat *p= codec->pix_fmts;
00461 for(; *p!=-1; p++){
00462 if(*p == c->pix_fmt)
00463 break;
00464 }
00465 if(*p == -1)
00466 c->pix_fmt = codec->pix_fmts[0];
00467 }
00468
00469 if (avcodec_open(c, codec) < 0) {
00470 c = NULL;
00471 asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
00472 "%s:%s: could not open codec\n",
00473 driverName, functionName);
00474 return;
00475 }
00476 }
00477
00478
00479 this->allocScArray(2 * size);
00480
00481
00482 scPicture->quality = 3276 - (int) (quality * 32.76);
00483 if (scPicture->quality < 0) scPicture->quality = 0;
00484 if (scPicture->quality > 32767) scPicture->quality = 32768;
00485
00486
00487 if (formatArray(pArray, this->pasynUserSelf, this->inPicture,
00488 &(this->ctx), this->c, this->scPicture) != asynSuccess) {
00489 asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
00490 "%s:%s: Could not format array for correct pix_fmt for codec\n",
00491 driverName, functionName);
00492
00493 this->lock();
00494 return;
00495 }
00496
00497
00498 pthread_mutex_lock(&this->mutex);
00499
00500
00501 if (this->jpeg) {
00502 this->jpeg->release();
00503 }
00504
00505
00506 this->jpeg = this->pNDArrayPool->alloc(1, &size, NDInt8, 0, NULL);
00507 this->jpeg->dims[0].size = avcodec_encode_video(c, (uint8_t*)this->jpeg->pData, c->width * c->height, scPicture);
00508
00509
00510
00511 for (int i=0; i<config.server_maxconn; i++) {
00512 pthread_cond_signal(&(this->cond[i]));
00513 }
00514 pthread_mutex_unlock(&this->mutex);
00515
00516
00517 this->lock();
00518
00519
00520 callParamCallbacks(0, 0);
00521
00522
00523
00524
00525 }
00526
00548 ffmpegStream::ffmpegStream(const char *portName, int queueSize, int blockingCallbacks,
00549 const char *NDArrayPort, int NDArrayAddr, int maxBuffers, int maxMemory,
00550 int priority, int stackSize)
00551
00552
00553
00554 : NDPluginDriver(portName, queueSize, blockingCallbacks,
00555 NDArrayPort, NDArrayAddr, 1, NUM_FFMPEG_SERVER_PARAMS, maxBuffers, maxMemory,
00556 asynGenericPointerMask,
00557 asynGenericPointerMask,
00558 0, 1, priority, stackSize < 128000 ? 128000 : stackSize)
00559 {
00560 char host[64] = "";
00561 char url[256] = "";
00562 asynStatus status;
00563 this->jpeg = NULL;
00564 this->scArray = NULL;
00565 this->nclients = 0;
00566 this->c = NULL;
00567 this->codec = NULL;
00568 this->inPicture = NULL;
00569 this->scPicture = NULL;
00570 this->ctx = NULL;
00571 this->cond = NULL;
00572
00573
00574 createParam(ffmpegServerQualityString, asynParamInt32, &ffmpegServerQuality);
00575 createParam(ffmpegServerFalseColString, asynParamInt32, &ffmpegServerFalseCol);
00576 createParam(ffmpegServerHttpPortString, asynParamInt32, &ffmpegServerHttpPort);
00577 createParam(ffmpegServerHostString, asynParamOctet, &ffmpegServerHost);
00578 createParam(ffmpegServerJpgUrlString, asynParamOctet, &ffmpegServerJpgUrl);
00579 createParam(ffmpegServerMjpgUrlString, asynParamOctet, &ffmpegServerMjpgUrl);
00580 createParam(ffmpegServerClientsString, asynParamInt32, &ffmpegServerClients);
00581 createParam(ffmpegServerAlwaysOnString, asynParamInt32, &ffmpegServerAlwaysOn);
00582 createParam(ffmpegServerMaxWString, asynParamInt32, &ffmpegServerMaxW);
00583 createParam(ffmpegServerMaxHString, asynParamInt32, &ffmpegServerMaxH);
00584
00585
00586 status = connectToArrayPort();
00587
00588
00589 setIntegerParam(0, ffmpegServerHttpPort, config.server_port);
00590 setIntegerParam(0, ffmpegServerClients, 0);
00591
00592
00593 setStringParam(NDPluginDriverPluginType, "ffmpegServer");
00594
00595
00596 gethostname(host, 64);
00597 setStringParam(ffmpegServerHost, host);
00598 sprintf(url, "http://%s:%d/%s.jpg", host, config.server_port, portName);
00599 setStringParam(ffmpegServerJpgUrl, url);
00600 sprintf(url, "http://%s:%d/%s.mjpg", host, config.server_port, portName);
00601 setStringParam(ffmpegServerMjpgUrl, url);
00602
00603
00604 ffmpegInitialise();
00605
00606
00607 inPicture = avcodec_alloc_frame();
00608 scPicture = avcodec_alloc_frame();
00609
00610
00611 codec = avcodec_find_encoder(CODEC_ID_MJPEG);
00612 if (!codec) {
00613 fprintf(stderr, "MJPG codec not found\n");
00614 exit(1);
00615 }
00616
00617
00618 pthread_mutex_init(&(this->mutex), NULL);
00619 this->cond = (pthread_cond_t *) calloc(config.server_maxconn, sizeof(pthread_cond_t));
00620 for (int i=0; i<config.server_maxconn; i++) {
00621 pthread_cond_init(&(this->cond[i]), NULL);
00622 }
00623 }
00624
00629 extern "C" int ffmpegStreamConfigure(const char *portName, int queueSize, int blockingCallbacks,
00630 const char *NDArrayPort, int NDArrayAddr, int maxBuffers, int maxMemory,
00631 int priority, int stackSize)
00632 {
00633 if (nstreams+1 > MAX_FFMPEG_STREAMS) {
00634 printf("%s:ffmpegStreamConfigure: Can only create %d streams\n",
00635 driverName, MAX_FFMPEG_STREAMS);
00636 return(asynError);
00637 }
00638 streams[nstreams++] = new ffmpegStream(portName, queueSize, blockingCallbacks, NDArrayPort, NDArrayAddr, maxBuffers, maxMemory, priority, stackSize);
00639 return(asynSuccess);
00640 }
00641
00642
00643 static const iocshArg streamArg0 = { "portName",iocshArgString};
00644 static const iocshArg streamArg1 = { "frame queue size",iocshArgInt};
00645 static const iocshArg streamArg2 = { "blocking callbacks",iocshArgInt};
00646 static const iocshArg streamArg3 = { "NDArray Port",iocshArgString};
00647 static const iocshArg streamArg4 = { "NDArray Addr",iocshArgInt};
00648 static const iocshArg streamArg5 = { "Max Buffers",iocshArgInt};
00649 static const iocshArg streamArg6 = { "Max memory",iocshArgInt};
00650 static const iocshArg streamArg7 = { "priority",iocshArgInt};
00651 static const iocshArg streamArg8 = { "stackSize",iocshArgInt};
00652 static const iocshArg * const streamArgs[] = {&streamArg0,
00653 &streamArg1,
00654 &streamArg2,
00655 &streamArg3,
00656 &streamArg4,
00657 &streamArg5,
00658 &streamArg6,
00659 &streamArg7,
00660 &streamArg8};
00661
00662 static const iocshFuncDef streamFuncDef = {"ffmpegStreamConfigure",9,streamArgs};
00663
00664 static void streamCallFunc(const iocshArgBuf *args)
00665 {
00666 ffmpegStreamConfigure(args[0].sval, args[1].ival, args[2].ival, args[3].sval, args[4].ival, args[5].ival, args[6].ival, args[7].ival, args[8].ival);
00667 }
00668
00669 static const iocshArg serverArg0 = { "Http Port",iocshArgInt};
00670 static const iocshArg * const serverArgs[] = {&serverArg0};
00671 static const iocshFuncDef serverFuncDef = {"ffmpegServerConfigure",1,serverArgs};
00672
00673 static void serverCallFunc(const iocshArgBuf *args)
00674 {
00675 ffmpegServerConfigure(args[0].ival);
00676 }
00677
00679 extern "C" void ffmpegServerRegister(void)
00680 {
00681 iocshRegister(&streamFuncDef,streamCallFunc);
00682 iocshRegister(&serverFuncDef,serverCallFunc);
00683 }
00684
00685 extern "C" {
00686 epicsExportRegistrar(ffmpegServerRegister);
00687 }