ffserver.c 126 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046
  1. /*
  2. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multiple format streaming server based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #if !HAVE_CLOSESOCKET
  26. #define closesocket close
  27. #endif
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include "libavformat/avformat.h"
  32. /* FIXME: those are internal headers, ffserver _really_ shouldn't use them */
  33. #include "libavformat/ffm.h"
  34. #include "libavformat/network.h"
  35. #include "libavformat/os_support.h"
  36. #include "libavformat/rtpdec.h"
  37. #include "libavformat/rtpproto.h"
  38. #include "libavformat/rtsp.h"
  39. #include "libavformat/rtspcodes.h"
  40. #include "libavformat/avio_internal.h"
  41. #include "libavformat/internal.h"
  42. #include "libavformat/url.h"
  43. #include "libavutil/avassert.h"
  44. #include "libavutil/avstring.h"
  45. #include "libavutil/lfg.h"
  46. #include "libavutil/dict.h"
  47. #include "libavutil/intreadwrite.h"
  48. #include "libavutil/mathematics.h"
  49. #include "libavutil/random_seed.h"
  50. #include "libavutil/parseutils.h"
  51. #include "libavutil/opt.h"
  52. #include "libavutil/time.h"
  53. #include <stdarg.h>
  54. #if HAVE_UNISTD_H
  55. #include <unistd.h>
  56. #endif
  57. #include <fcntl.h>
  58. #include <sys/ioctl.h>
  59. #if HAVE_POLL_H
  60. #include <poll.h>
  61. #endif
  62. #include <errno.h>
  63. #include <time.h>
  64. #include <sys/wait.h>
  65. #include <signal.h>
  66. #include "cmdutils.h"
  67. #include "ffserver_config.h"
  68. #define PATH_LENGTH 1024
  69. const char program_name[] = "ffserver";
  70. const int program_birth_year = 2000;
  71. static const OptionDef options[];
  72. enum HTTPState {
  73. HTTPSTATE_WAIT_REQUEST,
  74. HTTPSTATE_SEND_HEADER,
  75. HTTPSTATE_SEND_DATA_HEADER,
  76. HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */
  77. HTTPSTATE_SEND_DATA_TRAILER,
  78. HTTPSTATE_RECEIVE_DATA,
  79. HTTPSTATE_WAIT_FEED, /* wait for data from the feed */
  80. HTTPSTATE_READY,
  81. RTSPSTATE_WAIT_REQUEST,
  82. RTSPSTATE_SEND_REPLY,
  83. RTSPSTATE_SEND_PACKET,
  84. };
  85. static const char * const http_state[] = {
  86. "HTTP_WAIT_REQUEST",
  87. "HTTP_SEND_HEADER",
  88. "SEND_DATA_HEADER",
  89. "SEND_DATA",
  90. "SEND_DATA_TRAILER",
  91. "RECEIVE_DATA",
  92. "WAIT_FEED",
  93. "READY",
  94. "RTSP_WAIT_REQUEST",
  95. "RTSP_SEND_REPLY",
  96. "RTSP_SEND_PACKET",
  97. };
  98. #define IOBUFFER_INIT_SIZE 8192
  99. /* timeouts are in ms */
  100. #define HTTP_REQUEST_TIMEOUT (15 * 1000)
  101. #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000)
  102. #define SYNC_TIMEOUT (10 * 1000)
  103. typedef struct RTSPActionServerSetup {
  104. uint32_t ipaddr;
  105. char transport_option[512];
  106. } RTSPActionServerSetup;
  107. typedef struct {
  108. int64_t count1, count2;
  109. int64_t time1, time2;
  110. } DataRateData;
  111. /* context associated with one connection */
  112. typedef struct HTTPContext {
  113. enum HTTPState state;
  114. int fd; /* socket file descriptor */
  115. struct sockaddr_in from_addr; /* origin */
  116. struct pollfd *poll_entry; /* used when polling */
  117. int64_t timeout;
  118. uint8_t *buffer_ptr, *buffer_end;
  119. int http_error;
  120. int post;
  121. int chunked_encoding;
  122. int chunk_size; /* 0 if it needs to be read */
  123. struct HTTPContext *next;
  124. int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */
  125. int64_t data_count;
  126. /* feed input */
  127. int feed_fd;
  128. /* input format handling */
  129. AVFormatContext *fmt_in;
  130. int64_t start_time; /* In milliseconds - this wraps fairly often */
  131. int64_t first_pts; /* initial pts value */
  132. int64_t cur_pts; /* current pts value from the stream in us */
  133. int64_t cur_frame_duration; /* duration of the current frame in us */
  134. int cur_frame_bytes; /* output frame size, needed to compute
  135. the time at which we send each
  136. packet */
  137. int pts_stream_index; /* stream we choose as clock reference */
  138. int64_t cur_clock; /* current clock reference value in us */
  139. /* output format handling */
  140. struct FFServerStream *stream;
  141. /* -1 is invalid stream */
  142. int feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  143. int switch_feed_streams[FFSERVER_MAX_STREAMS]; /* index of streams in the feed */
  144. int switch_pending;
  145. AVFormatContext fmt_ctx; /* instance of FFServerStream for one user */
  146. int last_packet_sent; /* true if last data packet was sent */
  147. int suppress_log;
  148. DataRateData datarate;
  149. int wmp_client_id;
  150. char protocol[16];
  151. char method[16];
  152. char url[128];
  153. int buffer_size;
  154. uint8_t *buffer;
  155. int is_packetized; /* if true, the stream is packetized */
  156. int packet_stream_index; /* current stream for output in state machine */
  157. /* RTSP state specific */
  158. uint8_t *pb_buffer; /* XXX: use that in all the code */
  159. AVIOContext *pb;
  160. int seq; /* RTSP sequence number */
  161. /* RTP state specific */
  162. enum RTSPLowerTransport rtp_protocol;
  163. char session_id[32]; /* session id */
  164. AVFormatContext *rtp_ctx[FFSERVER_MAX_STREAMS];
  165. /* RTP/UDP specific */
  166. URLContext *rtp_handles[FFSERVER_MAX_STREAMS];
  167. /* RTP/TCP specific */
  168. struct HTTPContext *rtsp_c;
  169. uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end;
  170. } HTTPContext;
  171. typedef struct FeedData {
  172. long long data_count;
  173. float avg_frame_size; /* frame size averaged over last frames with exponential mean */
  174. } FeedData;
  175. static HTTPContext *first_http_ctx;
  176. static FFServerConfig config = {
  177. .nb_max_http_connections = 2000,
  178. .nb_max_connections = 5,
  179. .max_bandwidth = 1000,
  180. .use_defaults = 1,
  181. };
  182. static void new_connection(int server_fd, int is_rtsp);
  183. static void close_connection(HTTPContext *c);
  184. /* HTTP handling */
  185. static int handle_connection(HTTPContext *c);
  186. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream);
  187. static void compute_status(HTTPContext *c);
  188. static int open_input_stream(HTTPContext *c, const char *info);
  189. static int http_parse_request(HTTPContext *c);
  190. static int http_send_data(HTTPContext *c);
  191. static int http_start_receive_data(HTTPContext *c);
  192. static int http_receive_data(HTTPContext *c);
  193. /* RTSP handling */
  194. static int rtsp_parse_request(HTTPContext *c);
  195. static void rtsp_cmd_describe(HTTPContext *c, const char *url);
  196. static void rtsp_cmd_options(HTTPContext *c, const char *url);
  197. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  198. RTSPMessageHeader *h);
  199. static void rtsp_cmd_play(HTTPContext *c, const char *url,
  200. RTSPMessageHeader *h);
  201. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  202. RTSPMessageHeader *h, int pause_only);
  203. /* SDP handling */
  204. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  205. struct in_addr my_ip);
  206. /* RTP handling */
  207. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  208. FFServerStream *stream,
  209. const char *session_id,
  210. enum RTSPLowerTransport rtp_protocol);
  211. static int rtp_new_av_stream(HTTPContext *c,
  212. int stream_index, struct sockaddr_in *dest_addr,
  213. HTTPContext *rtsp_c);
  214. /* utils */
  215. static size_t htmlencode (const char *src, char **dest);
  216. static inline void cp_html_entity (char *buffer, const char *entity);
  217. static inline int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs,
  218. int stream);
  219. static const char *my_program_name;
  220. static int no_launch;
  221. static int need_to_start_children;
  222. /* maximum number of simultaneous HTTP connections */
  223. static unsigned int nb_connections;
  224. static uint64_t current_bandwidth;
  225. /* Making this global saves on passing it around everywhere */
  226. static int64_t cur_time;
  227. static AVLFG random_state;
  228. static FILE *logfile = NULL;
  229. static inline void cp_html_entity (char *buffer, const char *entity) {
  230. if (!buffer || !entity)
  231. return;
  232. while (*entity)
  233. *buffer++ = *entity++;
  234. }
  235. /**
  236. * Substitutes known conflicting chars on a text string with
  237. * their corresponding HTML entities.
  238. *
  239. * Returns the number of bytes in the 'encoded' representation
  240. * not including the terminating NUL.
  241. */
  242. static size_t htmlencode (const char *src, char **dest) {
  243. const char *amp = "&amp;";
  244. const char *lt = "&lt;";
  245. const char *gt = "&gt;";
  246. const char *start;
  247. char *tmp;
  248. size_t final_size = 0;
  249. if (!src)
  250. return 0;
  251. start = src;
  252. /* Compute needed dest size */
  253. while (*src != '\0') {
  254. switch(*src) {
  255. case 38: /* & */
  256. final_size += 5;
  257. break;
  258. case 60: /* < */
  259. case 62: /* > */
  260. final_size += 4;
  261. break;
  262. default:
  263. final_size++;
  264. }
  265. src++;
  266. }
  267. src = start;
  268. *dest = av_mallocz(final_size + 1);
  269. if (!*dest)
  270. return 0;
  271. /* Build dest */
  272. tmp = *dest;
  273. while (*src != '\0') {
  274. switch(*src) {
  275. case 38: /* & */
  276. cp_html_entity (tmp, amp);
  277. tmp += 5;
  278. break;
  279. case 60: /* < */
  280. cp_html_entity (tmp, lt);
  281. tmp += 4;
  282. break;
  283. case 62: /* > */
  284. cp_html_entity (tmp, gt);
  285. tmp += 4;
  286. break;
  287. default:
  288. *tmp = *src;
  289. tmp += 1;
  290. }
  291. src++;
  292. }
  293. *tmp = '\0';
  294. return final_size;
  295. }
  296. static int64_t ffm_read_write_index(int fd)
  297. {
  298. uint8_t buf[8];
  299. if (lseek(fd, 8, SEEK_SET) < 0)
  300. return AVERROR(EIO);
  301. if (read(fd, buf, 8) != 8)
  302. return AVERROR(EIO);
  303. return AV_RB64(buf);
  304. }
  305. static int ffm_write_write_index(int fd, int64_t pos)
  306. {
  307. uint8_t buf[8];
  308. int i;
  309. for(i=0;i<8;i++)
  310. buf[i] = (pos >> (56 - i * 8)) & 0xff;
  311. if (lseek(fd, 8, SEEK_SET) < 0)
  312. goto bail_eio;
  313. if (write(fd, buf, 8) != 8)
  314. goto bail_eio;
  315. return 8;
  316. bail_eio:
  317. return AVERROR(EIO);
  318. }
  319. static void ffm_set_write_index(AVFormatContext *s, int64_t pos,
  320. int64_t file_size)
  321. {
  322. av_opt_set_int(s, "server_attached", 1, AV_OPT_SEARCH_CHILDREN);
  323. av_opt_set_int(s, "ffm_write_index", pos, AV_OPT_SEARCH_CHILDREN);
  324. av_opt_set_int(s, "ffm_file_size", file_size, AV_OPT_SEARCH_CHILDREN);
  325. }
  326. static char *ctime1(char *buf2, size_t buf_size)
  327. {
  328. time_t ti;
  329. char *p;
  330. ti = time(NULL);
  331. p = ctime(&ti);
  332. if (!p || !*p) {
  333. *buf2 = '\0';
  334. return buf2;
  335. }
  336. av_strlcpy(buf2, p, buf_size);
  337. p = buf2 + strlen(buf2) - 1;
  338. if (*p == '\n')
  339. *p = '\0';
  340. return buf2;
  341. }
  342. static void http_vlog(const char *fmt, va_list vargs)
  343. {
  344. static int print_prefix = 1;
  345. char buf[32];
  346. if (!logfile)
  347. return;
  348. if (print_prefix) {
  349. ctime1(buf, sizeof(buf));
  350. fprintf(logfile, "%s ", buf);
  351. }
  352. print_prefix = strstr(fmt, "\n") != NULL;
  353. vfprintf(logfile, fmt, vargs);
  354. fflush(logfile);
  355. }
  356. #ifdef __GNUC__
  357. __attribute__ ((format (printf, 1, 2)))
  358. #endif
  359. static void http_log(const char *fmt, ...)
  360. {
  361. va_list vargs;
  362. va_start(vargs, fmt);
  363. http_vlog(fmt, vargs);
  364. va_end(vargs);
  365. }
  366. static void http_av_log(void *ptr, int level, const char *fmt, va_list vargs)
  367. {
  368. static int print_prefix = 1;
  369. AVClass *avc = ptr ? *(AVClass**)ptr : NULL;
  370. if (level > av_log_get_level())
  371. return;
  372. if (print_prefix && avc)
  373. http_log("[%s @ %p]", avc->item_name(ptr), ptr);
  374. print_prefix = strstr(fmt, "\n") != NULL;
  375. http_vlog(fmt, vargs);
  376. }
  377. static void log_connection(HTTPContext *c)
  378. {
  379. if (c->suppress_log)
  380. return;
  381. http_log("%s - - [%s] \"%s %s\" %d %"PRId64"\n",
  382. inet_ntoa(c->from_addr.sin_addr), c->method, c->url,
  383. c->protocol, (c->http_error ? c->http_error : 200), c->data_count);
  384. }
  385. static void update_datarate(DataRateData *drd, int64_t count)
  386. {
  387. if (!drd->time1 && !drd->count1) {
  388. drd->time1 = drd->time2 = cur_time;
  389. drd->count1 = drd->count2 = count;
  390. } else if (cur_time - drd->time2 > 5000) {
  391. drd->time1 = drd->time2;
  392. drd->count1 = drd->count2;
  393. drd->time2 = cur_time;
  394. drd->count2 = count;
  395. }
  396. }
  397. /* In bytes per second */
  398. static int compute_datarate(DataRateData *drd, int64_t count)
  399. {
  400. if (cur_time == drd->time1)
  401. return 0;
  402. return ((count - drd->count1) * 1000) / (cur_time - drd->time1);
  403. }
  404. static void start_children(FFServerStream *feed)
  405. {
  406. char *pathname;
  407. char *slash;
  408. int i;
  409. size_t cmd_length;
  410. if (no_launch)
  411. return;
  412. cmd_length = strlen(my_program_name);
  413. /**
  414. * FIXME: WIP Safeguard. Remove after clearing all harcoded
  415. * '1024' path lengths
  416. */
  417. if (cmd_length > PATH_LENGTH - 1) {
  418. http_log("Could not start children. Command line: '%s' exceeds "
  419. "path length limit (%d)\n", my_program_name, PATH_LENGTH);
  420. return;
  421. }
  422. pathname = av_strdup (my_program_name);
  423. if (!pathname) {
  424. http_log("Could not allocate memory for children cmd line\n");
  425. return;
  426. }
  427. /* replace "ffserver" with "ffmpeg" in the path of current
  428. * program. Ignore user provided path */
  429. slash = strrchr(pathname, '/');
  430. if (!slash)
  431. slash = pathname;
  432. else
  433. slash++;
  434. strcpy(slash, "ffmpeg");
  435. for (; feed; feed = feed->next) {
  436. if (!feed->child_argv || feed->pid)
  437. continue;
  438. feed->pid_start = time(0);
  439. feed->pid = fork();
  440. if (feed->pid < 0) {
  441. http_log("Unable to create children: %s\n", strerror(errno));
  442. av_free (pathname);
  443. exit(EXIT_FAILURE);
  444. }
  445. if (feed->pid)
  446. continue;
  447. /* In child */
  448. http_log("Launch command line: ");
  449. http_log("%s ", pathname);
  450. for (i = 1; feed->child_argv[i] && feed->child_argv[i][0]; i++)
  451. http_log("%s ", feed->child_argv[i]);
  452. http_log("\n");
  453. for (i = 3; i < 256; i++)
  454. close(i);
  455. if (!config.debug) {
  456. if (!freopen("/dev/null", "r", stdin))
  457. http_log("failed to redirect STDIN to /dev/null\n;");
  458. if (!freopen("/dev/null", "w", stdout))
  459. http_log("failed to redirect STDOUT to /dev/null\n;");
  460. if (!freopen("/dev/null", "w", stderr))
  461. http_log("failed to redirect STDERR to /dev/null\n;");
  462. }
  463. signal(SIGPIPE, SIG_DFL);
  464. execvp(pathname, feed->child_argv);
  465. av_free (pathname);
  466. _exit(1);
  467. }
  468. av_free (pathname);
  469. }
  470. /* open a listening socket */
  471. static int socket_open_listen(struct sockaddr_in *my_addr)
  472. {
  473. int server_fd, tmp;
  474. server_fd = socket(AF_INET,SOCK_STREAM,0);
  475. if (server_fd < 0) {
  476. perror ("socket");
  477. return -1;
  478. }
  479. tmp = 1;
  480. if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)))
  481. av_log(NULL, AV_LOG_WARNING, "setsockopt SO_REUSEADDR failed\n");
  482. my_addr->sin_family = AF_INET;
  483. if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) {
  484. char bindmsg[32];
  485. snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)",
  486. ntohs(my_addr->sin_port));
  487. perror (bindmsg);
  488. goto fail;
  489. }
  490. if (listen (server_fd, 5) < 0) {
  491. perror ("listen");
  492. goto fail;
  493. }
  494. if (ff_socket_nonblock(server_fd, 1) < 0)
  495. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  496. return server_fd;
  497. fail:
  498. closesocket(server_fd);
  499. return -1;
  500. }
  501. /* start all multicast streams */
  502. static void start_multicast(void)
  503. {
  504. FFServerStream *stream;
  505. char session_id[32];
  506. HTTPContext *rtp_c;
  507. struct sockaddr_in dest_addr = {0};
  508. int default_port, stream_index;
  509. unsigned int random0, random1;
  510. default_port = 6000;
  511. for(stream = config.first_stream; stream; stream = stream->next) {
  512. if (!stream->is_multicast)
  513. continue;
  514. random0 = av_lfg_get(&random_state);
  515. random1 = av_lfg_get(&random_state);
  516. /* open the RTP connection */
  517. snprintf(session_id, sizeof(session_id), "%08x%08x", random0, random1);
  518. /* choose a port if none given */
  519. if (stream->multicast_port == 0) {
  520. stream->multicast_port = default_port;
  521. default_port += 100;
  522. }
  523. dest_addr.sin_family = AF_INET;
  524. dest_addr.sin_addr = stream->multicast_ip;
  525. dest_addr.sin_port = htons(stream->multicast_port);
  526. rtp_c = rtp_new_connection(&dest_addr, stream, session_id,
  527. RTSP_LOWER_TRANSPORT_UDP_MULTICAST);
  528. if (!rtp_c)
  529. continue;
  530. if (open_input_stream(rtp_c, "") < 0) {
  531. http_log("Could not open input stream for stream '%s'\n",
  532. stream->filename);
  533. continue;
  534. }
  535. /* open each RTP stream */
  536. for(stream_index = 0; stream_index < stream->nb_streams;
  537. stream_index++) {
  538. dest_addr.sin_port = htons(stream->multicast_port +
  539. 2 * stream_index);
  540. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) >= 0)
  541. continue;
  542. http_log("Could not open output stream '%s/streamid=%d'\n",
  543. stream->filename, stream_index);
  544. exit(1);
  545. }
  546. rtp_c->state = HTTPSTATE_SEND_DATA;
  547. }
  548. }
  549. /* main loop of the HTTP server */
  550. static int http_server(void)
  551. {
  552. int server_fd = 0, rtsp_server_fd = 0;
  553. int ret, delay;
  554. struct pollfd *poll_table, *poll_entry;
  555. HTTPContext *c, *c_next;
  556. poll_table = av_mallocz_array(config.nb_max_http_connections + 2,
  557. sizeof(*poll_table));
  558. if(!poll_table) {
  559. http_log("Impossible to allocate a poll table handling %d "
  560. "connections.\n", config.nb_max_http_connections);
  561. return -1;
  562. }
  563. if (config.http_addr.sin_port) {
  564. server_fd = socket_open_listen(&config.http_addr);
  565. if (server_fd < 0)
  566. goto quit;
  567. }
  568. if (config.rtsp_addr.sin_port) {
  569. rtsp_server_fd = socket_open_listen(&config.rtsp_addr);
  570. if (rtsp_server_fd < 0) {
  571. closesocket(server_fd);
  572. goto quit;
  573. }
  574. }
  575. if (!rtsp_server_fd && !server_fd) {
  576. http_log("HTTP and RTSP disabled.\n");
  577. goto quit;
  578. }
  579. http_log("FFserver started.\n");
  580. start_children(config.first_feed);
  581. start_multicast();
  582. for(;;) {
  583. poll_entry = poll_table;
  584. if (server_fd) {
  585. poll_entry->fd = server_fd;
  586. poll_entry->events = POLLIN;
  587. poll_entry++;
  588. }
  589. if (rtsp_server_fd) {
  590. poll_entry->fd = rtsp_server_fd;
  591. poll_entry->events = POLLIN;
  592. poll_entry++;
  593. }
  594. /* wait for events on each HTTP handle */
  595. c = first_http_ctx;
  596. delay = 1000;
  597. while (c) {
  598. int fd;
  599. fd = c->fd;
  600. switch(c->state) {
  601. case HTTPSTATE_SEND_HEADER:
  602. case RTSPSTATE_SEND_REPLY:
  603. case RTSPSTATE_SEND_PACKET:
  604. c->poll_entry = poll_entry;
  605. poll_entry->fd = fd;
  606. poll_entry->events = POLLOUT;
  607. poll_entry++;
  608. break;
  609. case HTTPSTATE_SEND_DATA_HEADER:
  610. case HTTPSTATE_SEND_DATA:
  611. case HTTPSTATE_SEND_DATA_TRAILER:
  612. if (!c->is_packetized) {
  613. /* for TCP, we output as much as we can
  614. * (may need to put a limit) */
  615. c->poll_entry = poll_entry;
  616. poll_entry->fd = fd;
  617. poll_entry->events = POLLOUT;
  618. poll_entry++;
  619. } else {
  620. /* when ffserver is doing the timing, we work by
  621. * looking at which packet needs to be sent every
  622. * 10 ms (one tick wait XXX: 10 ms assumed) */
  623. if (delay > 10)
  624. delay = 10;
  625. }
  626. break;
  627. case HTTPSTATE_WAIT_REQUEST:
  628. case HTTPSTATE_RECEIVE_DATA:
  629. case HTTPSTATE_WAIT_FEED:
  630. case RTSPSTATE_WAIT_REQUEST:
  631. /* need to catch errors */
  632. c->poll_entry = poll_entry;
  633. poll_entry->fd = fd;
  634. poll_entry->events = POLLIN;/* Maybe this will work */
  635. poll_entry++;
  636. break;
  637. default:
  638. c->poll_entry = NULL;
  639. break;
  640. }
  641. c = c->next;
  642. }
  643. /* wait for an event on one connection. We poll at least every
  644. * second to handle timeouts */
  645. do {
  646. ret = poll(poll_table, poll_entry - poll_table, delay);
  647. if (ret < 0 && ff_neterrno() != AVERROR(EAGAIN) &&
  648. ff_neterrno() != AVERROR(EINTR)) {
  649. goto quit;
  650. }
  651. } while (ret < 0);
  652. cur_time = av_gettime() / 1000;
  653. if (need_to_start_children) {
  654. need_to_start_children = 0;
  655. start_children(config.first_feed);
  656. }
  657. /* now handle the events */
  658. for(c = first_http_ctx; c; c = c_next) {
  659. c_next = c->next;
  660. if (handle_connection(c) < 0) {
  661. log_connection(c);
  662. /* close and free the connection */
  663. close_connection(c);
  664. }
  665. }
  666. poll_entry = poll_table;
  667. if (server_fd) {
  668. /* new HTTP connection request ? */
  669. if (poll_entry->revents & POLLIN)
  670. new_connection(server_fd, 0);
  671. poll_entry++;
  672. }
  673. if (rtsp_server_fd) {
  674. /* new RTSP connection request ? */
  675. if (poll_entry->revents & POLLIN)
  676. new_connection(rtsp_server_fd, 1);
  677. }
  678. }
  679. quit:
  680. av_free(poll_table);
  681. return -1;
  682. }
  683. /* start waiting for a new HTTP/RTSP request */
  684. static void start_wait_request(HTTPContext *c, int is_rtsp)
  685. {
  686. c->buffer_ptr = c->buffer;
  687. c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */
  688. c->state = is_rtsp ? RTSPSTATE_WAIT_REQUEST : HTTPSTATE_WAIT_REQUEST;
  689. c->timeout = cur_time +
  690. (is_rtsp ? RTSP_REQUEST_TIMEOUT : HTTP_REQUEST_TIMEOUT);
  691. }
  692. static void http_send_too_busy_reply(int fd)
  693. {
  694. char buffer[400];
  695. int len = snprintf(buffer, sizeof(buffer),
  696. "HTTP/1.0 503 Server too busy\r\n"
  697. "Content-type: text/html\r\n"
  698. "\r\n"
  699. "<!DOCTYPE html>\n"
  700. "<html><head><title>Too busy</title></head><body>\r\n"
  701. "<p>The server is too busy to serve your request at "
  702. "this time.</p>\r\n"
  703. "<p>The number of current connections is %u, and this "
  704. "exceeds the limit of %u.</p>\r\n"
  705. "</body></html>\r\n",
  706. nb_connections, config.nb_max_connections);
  707. av_assert0(len < sizeof(buffer));
  708. if (send(fd, buffer, len, 0) < len)
  709. av_log(NULL, AV_LOG_WARNING,
  710. "Could not send too-busy reply, send() failed\n");
  711. }
  712. static void new_connection(int server_fd, int is_rtsp)
  713. {
  714. struct sockaddr_in from_addr;
  715. socklen_t len;
  716. int fd;
  717. HTTPContext *c = NULL;
  718. len = sizeof(from_addr);
  719. fd = accept(server_fd, (struct sockaddr *)&from_addr,
  720. &len);
  721. if (fd < 0) {
  722. http_log("error during accept %s\n", strerror(errno));
  723. return;
  724. }
  725. if (ff_socket_nonblock(fd, 1) < 0)
  726. av_log(NULL, AV_LOG_WARNING, "ff_socket_nonblock failed\n");
  727. if (nb_connections >= config.nb_max_connections) {
  728. http_send_too_busy_reply(fd);
  729. goto fail;
  730. }
  731. /* add a new connection */
  732. c = av_mallocz(sizeof(HTTPContext));
  733. if (!c)
  734. goto fail;
  735. c->fd = fd;
  736. c->poll_entry = NULL;
  737. c->from_addr = from_addr;
  738. c->buffer_size = IOBUFFER_INIT_SIZE;
  739. c->buffer = av_malloc(c->buffer_size);
  740. if (!c->buffer)
  741. goto fail;
  742. c->next = first_http_ctx;
  743. first_http_ctx = c;
  744. nb_connections++;
  745. start_wait_request(c, is_rtsp);
  746. return;
  747. fail:
  748. if (c) {
  749. av_freep(&c->buffer);
  750. av_free(c);
  751. }
  752. closesocket(fd);
  753. }
  754. static void close_connection(HTTPContext *c)
  755. {
  756. HTTPContext **cp, *c1;
  757. int i, nb_streams;
  758. AVFormatContext *ctx;
  759. AVStream *st;
  760. /* remove connection from list */
  761. cp = &first_http_ctx;
  762. while (*cp) {
  763. c1 = *cp;
  764. if (c1 == c)
  765. *cp = c->next;
  766. else
  767. cp = &c1->next;
  768. }
  769. /* remove references, if any (XXX: do it faster) */
  770. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  771. if (c1->rtsp_c == c)
  772. c1->rtsp_c = NULL;
  773. }
  774. /* remove connection associated resources */
  775. if (c->fd >= 0)
  776. closesocket(c->fd);
  777. if (c->fmt_in) {
  778. /* close each frame parser */
  779. for(i=0;i<c->fmt_in->nb_streams;i++) {
  780. st = c->fmt_in->streams[i];
  781. if (st->codec->codec)
  782. avcodec_close(st->codec);
  783. }
  784. avformat_close_input(&c->fmt_in);
  785. }
  786. /* free RTP output streams if any */
  787. nb_streams = 0;
  788. if (c->stream)
  789. nb_streams = c->stream->nb_streams;
  790. for(i=0;i<nb_streams;i++) {
  791. ctx = c->rtp_ctx[i];
  792. if (ctx) {
  793. av_write_trailer(ctx);
  794. av_dict_free(&ctx->metadata);
  795. av_freep(&ctx->streams[0]);
  796. av_freep(&ctx);
  797. }
  798. ffurl_close(c->rtp_handles[i]);
  799. }
  800. ctx = &c->fmt_ctx;
  801. if (!c->last_packet_sent && c->state == HTTPSTATE_SEND_DATA_TRAILER) {
  802. /* prepare header */
  803. if (ctx->oformat && avio_open_dyn_buf(&ctx->pb) >= 0) {
  804. av_write_trailer(ctx);
  805. av_freep(&c->pb_buffer);
  806. avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  807. }
  808. }
  809. for(i=0; i<ctx->nb_streams; i++)
  810. av_freep(&ctx->streams[i]);
  811. av_freep(&ctx->streams);
  812. av_freep(&ctx->priv_data);
  813. if (c->stream && !c->post && c->stream->stream_type == STREAM_TYPE_LIVE)
  814. current_bandwidth -= c->stream->bandwidth;
  815. /* signal that there is no feed if we are the feeder socket */
  816. if (c->state == HTTPSTATE_RECEIVE_DATA && c->stream) {
  817. c->stream->feed_opened = 0;
  818. close(c->feed_fd);
  819. }
  820. av_freep(&c->pb_buffer);
  821. av_freep(&c->packet_buffer);
  822. av_freep(&c->buffer);
  823. av_free(c);
  824. nb_connections--;
  825. }
  826. static int handle_connection(HTTPContext *c)
  827. {
  828. int len, ret;
  829. uint8_t *ptr;
  830. switch(c->state) {
  831. case HTTPSTATE_WAIT_REQUEST:
  832. case RTSPSTATE_WAIT_REQUEST:
  833. /* timeout ? */
  834. if ((c->timeout - cur_time) < 0)
  835. return -1;
  836. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  837. return -1;
  838. /* no need to read if no events */
  839. if (!(c->poll_entry->revents & POLLIN))
  840. return 0;
  841. /* read the data */
  842. read_loop:
  843. if (!(len = recv(c->fd, c->buffer_ptr, 1, 0)))
  844. return -1;
  845. if (len < 0) {
  846. if (ff_neterrno() != AVERROR(EAGAIN) &&
  847. ff_neterrno() != AVERROR(EINTR))
  848. return -1;
  849. break;
  850. }
  851. /* search for end of request. */
  852. c->buffer_ptr += len;
  853. ptr = c->buffer_ptr;
  854. if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||
  855. (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {
  856. /* request found : parse it and reply */
  857. if (c->state == HTTPSTATE_WAIT_REQUEST)
  858. ret = http_parse_request(c);
  859. else
  860. ret = rtsp_parse_request(c);
  861. if (ret < 0)
  862. return -1;
  863. } else if (ptr >= c->buffer_end) {
  864. /* request too long: cannot do anything */
  865. return -1;
  866. } else goto read_loop;
  867. break;
  868. case HTTPSTATE_SEND_HEADER:
  869. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  870. return -1;
  871. /* no need to write if no events */
  872. if (!(c->poll_entry->revents & POLLOUT))
  873. return 0;
  874. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  875. if (len < 0) {
  876. if (ff_neterrno() != AVERROR(EAGAIN) &&
  877. ff_neterrno() != AVERROR(EINTR)) {
  878. goto close_connection;
  879. }
  880. break;
  881. }
  882. c->buffer_ptr += len;
  883. if (c->stream)
  884. c->stream->bytes_served += len;
  885. c->data_count += len;
  886. if (c->buffer_ptr >= c->buffer_end) {
  887. av_freep(&c->pb_buffer);
  888. /* if error, exit */
  889. if (c->http_error)
  890. return -1;
  891. /* all the buffer was sent : synchronize to the incoming
  892. * stream */
  893. c->state = HTTPSTATE_SEND_DATA_HEADER;
  894. c->buffer_ptr = c->buffer_end = c->buffer;
  895. }
  896. break;
  897. case HTTPSTATE_SEND_DATA:
  898. case HTTPSTATE_SEND_DATA_HEADER:
  899. case HTTPSTATE_SEND_DATA_TRAILER:
  900. /* for packetized output, we consider we can always write (the
  901. * input streams set the speed). It may be better to verify
  902. * that we do not rely too much on the kernel queues */
  903. if (!c->is_packetized) {
  904. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  905. return -1;
  906. /* no need to read if no events */
  907. if (!(c->poll_entry->revents & POLLOUT))
  908. return 0;
  909. }
  910. if (http_send_data(c) < 0)
  911. return -1;
  912. /* close connection if trailer sent */
  913. if (c->state == HTTPSTATE_SEND_DATA_TRAILER)
  914. return -1;
  915. /* Check if it is a single jpeg frame 123 */
  916. if (c->stream->single_frame && c->data_count > c->cur_frame_bytes && c->cur_frame_bytes > 0) {
  917. close_connection(c);
  918. }
  919. break;
  920. case HTTPSTATE_RECEIVE_DATA:
  921. /* no need to read if no events */
  922. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  923. return -1;
  924. if (!(c->poll_entry->revents & POLLIN))
  925. return 0;
  926. if (http_receive_data(c) < 0)
  927. return -1;
  928. break;
  929. case HTTPSTATE_WAIT_FEED:
  930. /* no need to read if no events */
  931. if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))
  932. return -1;
  933. /* nothing to do, we'll be waken up by incoming feed packets */
  934. break;
  935. case RTSPSTATE_SEND_REPLY:
  936. if (c->poll_entry->revents & (POLLERR | POLLHUP))
  937. goto close_connection;
  938. /* no need to write if no events */
  939. if (!(c->poll_entry->revents & POLLOUT))
  940. return 0;
  941. len = send(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr, 0);
  942. if (len < 0) {
  943. if (ff_neterrno() != AVERROR(EAGAIN) &&
  944. ff_neterrno() != AVERROR(EINTR)) {
  945. goto close_connection;
  946. }
  947. break;
  948. }
  949. c->buffer_ptr += len;
  950. c->data_count += len;
  951. if (c->buffer_ptr >= c->buffer_end) {
  952. /* all the buffer was sent : wait for a new request */
  953. av_freep(&c->pb_buffer);
  954. start_wait_request(c, 1);
  955. }
  956. break;
  957. case RTSPSTATE_SEND_PACKET:
  958. if (c->poll_entry->revents & (POLLERR | POLLHUP)) {
  959. av_freep(&c->packet_buffer);
  960. return -1;
  961. }
  962. /* no need to write if no events */
  963. if (!(c->poll_entry->revents & POLLOUT))
  964. return 0;
  965. len = send(c->fd, c->packet_buffer_ptr,
  966. c->packet_buffer_end - c->packet_buffer_ptr, 0);
  967. if (len < 0) {
  968. if (ff_neterrno() != AVERROR(EAGAIN) &&
  969. ff_neterrno() != AVERROR(EINTR)) {
  970. /* error : close connection */
  971. av_freep(&c->packet_buffer);
  972. return -1;
  973. }
  974. break;
  975. }
  976. c->packet_buffer_ptr += len;
  977. if (c->packet_buffer_ptr >= c->packet_buffer_end) {
  978. /* all the buffer was sent : wait for a new request */
  979. av_freep(&c->packet_buffer);
  980. c->state = RTSPSTATE_WAIT_REQUEST;
  981. }
  982. break;
  983. case HTTPSTATE_READY:
  984. /* nothing to do */
  985. break;
  986. default:
  987. return -1;
  988. }
  989. return 0;
  990. close_connection:
  991. av_freep(&c->pb_buffer);
  992. return -1;
  993. }
  994. static int extract_rates(char *rates, int ratelen, const char *request)
  995. {
  996. const char *p;
  997. for (p = request; *p && *p != '\r' && *p != '\n'; ) {
  998. if (av_strncasecmp(p, "Pragma:", 7) == 0) {
  999. const char *q = p + 7;
  1000. while (*q && *q != '\n' && av_isspace(*q))
  1001. q++;
  1002. if (av_strncasecmp(q, "stream-switch-entry=", 20) == 0) {
  1003. int stream_no;
  1004. int rate_no;
  1005. q += 20;
  1006. memset(rates, 0xff, ratelen);
  1007. while (1) {
  1008. while (*q && *q != '\n' && *q != ':')
  1009. q++;
  1010. if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2)
  1011. break;
  1012. stream_no--;
  1013. if (stream_no < ratelen && stream_no >= 0)
  1014. rates[stream_no] = rate_no;
  1015. while (*q && *q != '\n' && !av_isspace(*q))
  1016. q++;
  1017. }
  1018. return 1;
  1019. }
  1020. }
  1021. p = strchr(p, '\n');
  1022. if (!p)
  1023. break;
  1024. p++;
  1025. }
  1026. return 0;
  1027. }
  1028. static int find_stream_in_feed(FFServerStream *feed, AVCodecContext *codec,
  1029. int bit_rate)
  1030. {
  1031. int i;
  1032. int best_bitrate = 100000000;
  1033. int best = -1;
  1034. for (i = 0; i < feed->nb_streams; i++) {
  1035. AVCodecContext *feed_codec = feed->streams[i]->codec;
  1036. if (feed_codec->codec_id != codec->codec_id ||
  1037. feed_codec->sample_rate != codec->sample_rate ||
  1038. feed_codec->width != codec->width ||
  1039. feed_codec->height != codec->height)
  1040. continue;
  1041. /* Potential stream */
  1042. /* We want the fastest stream less than bit_rate, or the slowest
  1043. * faster than bit_rate
  1044. */
  1045. if (feed_codec->bit_rate <= bit_rate) {
  1046. if (best_bitrate > bit_rate ||
  1047. feed_codec->bit_rate > best_bitrate) {
  1048. best_bitrate = feed_codec->bit_rate;
  1049. best = i;
  1050. }
  1051. continue;
  1052. }
  1053. if (feed_codec->bit_rate < best_bitrate) {
  1054. best_bitrate = feed_codec->bit_rate;
  1055. best = i;
  1056. }
  1057. }
  1058. return best;
  1059. }
  1060. static int modify_current_stream(HTTPContext *c, char *rates)
  1061. {
  1062. int i;
  1063. FFServerStream *req = c->stream;
  1064. int action_required = 0;
  1065. /* Not much we can do for a feed */
  1066. if (!req->feed)
  1067. return 0;
  1068. for (i = 0; i < req->nb_streams; i++) {
  1069. AVCodecContext *codec = req->streams[i]->codec;
  1070. switch(rates[i]) {
  1071. case 0:
  1072. c->switch_feed_streams[i] = req->feed_streams[i];
  1073. break;
  1074. case 1:
  1075. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2);
  1076. break;
  1077. case 2:
  1078. /* Wants off or slow */
  1079. c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4);
  1080. #ifdef WANTS_OFF
  1081. /* This doesn't work well when it turns off the only stream! */
  1082. c->switch_feed_streams[i] = -2;
  1083. c->feed_streams[i] = -2;
  1084. #endif
  1085. break;
  1086. }
  1087. if (c->switch_feed_streams[i] >= 0 &&
  1088. c->switch_feed_streams[i] != c->feed_streams[i]) {
  1089. action_required = 1;
  1090. }
  1091. }
  1092. return action_required;
  1093. }
  1094. static void get_word(char *buf, int buf_size, const char **pp)
  1095. {
  1096. const char *p;
  1097. char *q;
  1098. p = *pp;
  1099. p += strspn(p, SPACE_CHARS);
  1100. q = buf;
  1101. while (!av_isspace(*p) && *p != '\0') {
  1102. if ((q - buf) < buf_size - 1)
  1103. *q++ = *p;
  1104. p++;
  1105. }
  1106. if (buf_size > 0)
  1107. *q = '\0';
  1108. *pp = p;
  1109. }
  1110. static FFServerIPAddressACL* parse_dynamic_acl(FFServerStream *stream,
  1111. HTTPContext *c)
  1112. {
  1113. FILE* f;
  1114. char line[1024];
  1115. char cmd[1024];
  1116. FFServerIPAddressACL *acl = NULL;
  1117. int line_num = 0;
  1118. const char *p;
  1119. f = fopen(stream->dynamic_acl, "r");
  1120. if (!f) {
  1121. perror(stream->dynamic_acl);
  1122. return NULL;
  1123. }
  1124. acl = av_mallocz(sizeof(FFServerIPAddressACL));
  1125. if (!acl) {
  1126. fclose(f);
  1127. return NULL;
  1128. }
  1129. /* Build ACL */
  1130. while (fgets(line, sizeof(line), f)) {
  1131. line_num++;
  1132. p = line;
  1133. while (av_isspace(*p))
  1134. p++;
  1135. if (*p == '\0' || *p == '#')
  1136. continue;
  1137. ffserver_get_arg(cmd, sizeof(cmd), &p);
  1138. if (!av_strcasecmp(cmd, "ACL"))
  1139. ffserver_parse_acl_row(NULL, NULL, acl, p, stream->dynamic_acl,
  1140. line_num);
  1141. }
  1142. fclose(f);
  1143. return acl;
  1144. }
  1145. static void free_acl_list(FFServerIPAddressACL *in_acl)
  1146. {
  1147. FFServerIPAddressACL *pacl, *pacl2;
  1148. pacl = in_acl;
  1149. while(pacl) {
  1150. pacl2 = pacl;
  1151. pacl = pacl->next;
  1152. av_freep(pacl2);
  1153. }
  1154. }
  1155. static int validate_acl_list(FFServerIPAddressACL *in_acl, HTTPContext *c)
  1156. {
  1157. enum FFServerIPAddressAction last_action = IP_DENY;
  1158. FFServerIPAddressACL *acl;
  1159. struct in_addr *src = &c->from_addr.sin_addr;
  1160. unsigned long src_addr = src->s_addr;
  1161. for (acl = in_acl; acl; acl = acl->next) {
  1162. if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr)
  1163. return (acl->action == IP_ALLOW) ? 1 : 0;
  1164. last_action = acl->action;
  1165. }
  1166. /* Nothing matched, so return not the last action */
  1167. return (last_action == IP_DENY) ? 1 : 0;
  1168. }
  1169. static int validate_acl(FFServerStream *stream, HTTPContext *c)
  1170. {
  1171. int ret = 0;
  1172. FFServerIPAddressACL *acl;
  1173. /* if stream->acl is null validate_acl_list will return 1 */
  1174. ret = validate_acl_list(stream->acl, c);
  1175. if (stream->dynamic_acl[0]) {
  1176. acl = parse_dynamic_acl(stream, c);
  1177. ret = validate_acl_list(acl, c);
  1178. free_acl_list(acl);
  1179. }
  1180. return ret;
  1181. }
  1182. /**
  1183. * compute the real filename of a file by matching it without its
  1184. * extensions to all the stream's filenames
  1185. */
  1186. static void compute_real_filename(char *filename, int max_size)
  1187. {
  1188. char file1[1024];
  1189. char file2[1024];
  1190. char *p;
  1191. FFServerStream *stream;
  1192. av_strlcpy(file1, filename, sizeof(file1));
  1193. p = strrchr(file1, '.');
  1194. if (p)
  1195. *p = '\0';
  1196. for(stream = config.first_stream; stream; stream = stream->next) {
  1197. av_strlcpy(file2, stream->filename, sizeof(file2));
  1198. p = strrchr(file2, '.');
  1199. if (p)
  1200. *p = '\0';
  1201. if (!strcmp(file1, file2)) {
  1202. av_strlcpy(filename, stream->filename, max_size);
  1203. break;
  1204. }
  1205. }
  1206. }
  1207. enum RedirType {
  1208. REDIR_NONE,
  1209. REDIR_ASX,
  1210. REDIR_RAM,
  1211. REDIR_ASF,
  1212. REDIR_RTSP,
  1213. REDIR_SDP,
  1214. };
  1215. /* parse HTTP request and prepare header */
  1216. static int http_parse_request(HTTPContext *c)
  1217. {
  1218. const char *p;
  1219. char *p1;
  1220. enum RedirType redir_type;
  1221. char cmd[32];
  1222. char info[1024], filename[1024];
  1223. char url[1024], *q;
  1224. char protocol[32];
  1225. char msg[1024];
  1226. char *encoded_msg = NULL;
  1227. const char *mime_type;
  1228. FFServerStream *stream;
  1229. int i;
  1230. char ratebuf[32];
  1231. const char *useragent = 0;
  1232. p = c->buffer;
  1233. get_word(cmd, sizeof(cmd), &p);
  1234. av_strlcpy(c->method, cmd, sizeof(c->method));
  1235. if (!strcmp(cmd, "GET"))
  1236. c->post = 0;
  1237. else if (!strcmp(cmd, "POST"))
  1238. c->post = 1;
  1239. else
  1240. return -1;
  1241. get_word(url, sizeof(url), &p);
  1242. av_strlcpy(c->url, url, sizeof(c->url));
  1243. get_word(protocol, sizeof(protocol), (const char **)&p);
  1244. if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1"))
  1245. return -1;
  1246. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  1247. if (config.debug)
  1248. http_log("%s - - New connection: %s %s\n",
  1249. inet_ntoa(c->from_addr.sin_addr), cmd, url);
  1250. /* find the filename and the optional info string in the request */
  1251. p1 = strchr(url, '?');
  1252. if (p1) {
  1253. av_strlcpy(info, p1, sizeof(info));
  1254. *p1 = '\0';
  1255. } else
  1256. info[0] = '\0';
  1257. av_strlcpy(filename, url + ((*url == '/') ? 1 : 0), sizeof(filename)-1);
  1258. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1259. if (av_strncasecmp(p, "User-Agent:", 11) == 0) {
  1260. useragent = p + 11;
  1261. if (*useragent && *useragent != '\n' && av_isspace(*useragent))
  1262. useragent++;
  1263. break;
  1264. }
  1265. p = strchr(p, '\n');
  1266. if (!p)
  1267. break;
  1268. p++;
  1269. }
  1270. redir_type = REDIR_NONE;
  1271. if (av_match_ext(filename, "asx")) {
  1272. redir_type = REDIR_ASX;
  1273. filename[strlen(filename)-1] = 'f';
  1274. } else if (av_match_ext(filename, "asf") &&
  1275. (!useragent || av_strncasecmp(useragent, "NSPlayer", 8))) {
  1276. /* if this isn't WMP or lookalike, return the redirector file */
  1277. redir_type = REDIR_ASF;
  1278. } else if (av_match_ext(filename, "rpm,ram")) {
  1279. redir_type = REDIR_RAM;
  1280. strcpy(filename + strlen(filename)-2, "m");
  1281. } else if (av_match_ext(filename, "rtsp")) {
  1282. redir_type = REDIR_RTSP;
  1283. compute_real_filename(filename, sizeof(filename) - 1);
  1284. } else if (av_match_ext(filename, "sdp")) {
  1285. redir_type = REDIR_SDP;
  1286. compute_real_filename(filename, sizeof(filename) - 1);
  1287. }
  1288. /* "redirect" request to index.html */
  1289. if (!strlen(filename))
  1290. av_strlcpy(filename, "index.html", sizeof(filename) - 1);
  1291. stream = config.first_stream;
  1292. while (stream) {
  1293. if (!strcmp(stream->filename, filename) && validate_acl(stream, c))
  1294. break;
  1295. stream = stream->next;
  1296. }
  1297. if (!stream) {
  1298. snprintf(msg, sizeof(msg), "File '%s' not found", url);
  1299. http_log("File '%s' not found\n", url);
  1300. goto send_error;
  1301. }
  1302. c->stream = stream;
  1303. memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams));
  1304. memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams));
  1305. if (stream->stream_type == STREAM_TYPE_REDIRECT) {
  1306. c->http_error = 301;
  1307. q = c->buffer;
  1308. snprintf(q, c->buffer_size,
  1309. "HTTP/1.0 301 Moved\r\n"
  1310. "Location: %s\r\n"
  1311. "Content-type: text/html\r\n"
  1312. "\r\n"
  1313. "<!DOCTYPE html>\n"
  1314. "<html><head><title>Moved</title></head><body>\r\n"
  1315. "You should be <a href=\"%s\">redirected</a>.\r\n"
  1316. "</body></html>\r\n",
  1317. stream->feed_filename, stream->feed_filename);
  1318. q += strlen(q);
  1319. /* prepare output buffer */
  1320. c->buffer_ptr = c->buffer;
  1321. c->buffer_end = q;
  1322. c->state = HTTPSTATE_SEND_HEADER;
  1323. return 0;
  1324. }
  1325. /* If this is WMP, get the rate information */
  1326. if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1327. if (modify_current_stream(c, ratebuf)) {
  1328. for (i = 0; i < FF_ARRAY_ELEMS(c->feed_streams); i++) {
  1329. if (c->switch_feed_streams[i] >= 0)
  1330. c->switch_feed_streams[i] = -1;
  1331. }
  1332. }
  1333. }
  1334. if (c->post == 0 && stream->stream_type == STREAM_TYPE_LIVE)
  1335. current_bandwidth += stream->bandwidth;
  1336. /* If already streaming this feed, do not let another feeder start */
  1337. if (stream->feed_opened) {
  1338. snprintf(msg, sizeof(msg), "This feed is already being received.");
  1339. http_log("Feed '%s' already being received\n", stream->feed_filename);
  1340. goto send_error;
  1341. }
  1342. if (c->post == 0 && config.max_bandwidth < current_bandwidth) {
  1343. c->http_error = 503;
  1344. q = c->buffer;
  1345. snprintf(q, c->buffer_size,
  1346. "HTTP/1.0 503 Server too busy\r\n"
  1347. "Content-type: text/html\r\n"
  1348. "\r\n"
  1349. "<!DOCTYPE html>\n"
  1350. "<html><head><title>Too busy</title></head><body>\r\n"
  1351. "<p>The server is too busy to serve your request at "
  1352. "this time.</p>\r\n"
  1353. "<p>The bandwidth being served (including your stream) "
  1354. "is %"PRIu64"kbit/s, and this exceeds the limit of "
  1355. "%"PRIu64"kbit/s.</p>\r\n"
  1356. "</body></html>\r\n",
  1357. current_bandwidth, config.max_bandwidth);
  1358. q += strlen(q);
  1359. /* prepare output buffer */
  1360. c->buffer_ptr = c->buffer;
  1361. c->buffer_end = q;
  1362. c->state = HTTPSTATE_SEND_HEADER;
  1363. return 0;
  1364. }
  1365. if (redir_type != REDIR_NONE) {
  1366. const char *hostinfo = 0;
  1367. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1368. if (av_strncasecmp(p, "Host:", 5) == 0) {
  1369. hostinfo = p + 5;
  1370. break;
  1371. }
  1372. p = strchr(p, '\n');
  1373. if (!p)
  1374. break;
  1375. p++;
  1376. }
  1377. if (hostinfo) {
  1378. char *eoh;
  1379. char hostbuf[260];
  1380. while (av_isspace(*hostinfo))
  1381. hostinfo++;
  1382. eoh = strchr(hostinfo, '\n');
  1383. if (eoh) {
  1384. if (eoh[-1] == '\r')
  1385. eoh--;
  1386. if (eoh - hostinfo < sizeof(hostbuf) - 1) {
  1387. memcpy(hostbuf, hostinfo, eoh - hostinfo);
  1388. hostbuf[eoh - hostinfo] = 0;
  1389. c->http_error = 200;
  1390. q = c->buffer;
  1391. switch(redir_type) {
  1392. case REDIR_ASX:
  1393. snprintf(q, c->buffer_size,
  1394. "HTTP/1.0 200 ASX Follows\r\n"
  1395. "Content-type: video/x-ms-asf\r\n"
  1396. "\r\n"
  1397. "<ASX Version=\"3\">\r\n"
  1398. //"<!-- Autogenerated by ffserver -->\r\n"
  1399. "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n"
  1400. "</ASX>\r\n", hostbuf, filename, info);
  1401. q += strlen(q);
  1402. break;
  1403. case REDIR_RAM:
  1404. snprintf(q, c->buffer_size,
  1405. "HTTP/1.0 200 RAM Follows\r\n"
  1406. "Content-type: audio/x-pn-realaudio\r\n"
  1407. "\r\n"
  1408. "# Autogenerated by ffserver\r\n"
  1409. "http://%s/%s%s\r\n", hostbuf, filename, info);
  1410. q += strlen(q);
  1411. break;
  1412. case REDIR_ASF:
  1413. snprintf(q, c->buffer_size,
  1414. "HTTP/1.0 200 ASF Redirect follows\r\n"
  1415. "Content-type: video/x-ms-asf\r\n"
  1416. "\r\n"
  1417. "[Reference]\r\n"
  1418. "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info);
  1419. q += strlen(q);
  1420. break;
  1421. case REDIR_RTSP:
  1422. {
  1423. char hostname[256], *p;
  1424. /* extract only hostname */
  1425. av_strlcpy(hostname, hostbuf, sizeof(hostname));
  1426. p = strrchr(hostname, ':');
  1427. if (p)
  1428. *p = '\0';
  1429. snprintf(q, c->buffer_size,
  1430. "HTTP/1.0 200 RTSP Redirect follows\r\n"
  1431. /* XXX: incorrect MIME type ? */
  1432. "Content-type: application/x-rtsp\r\n"
  1433. "\r\n"
  1434. "rtsp://%s:%d/%s\r\n", hostname, ntohs(config.rtsp_addr.sin_port), filename);
  1435. q += strlen(q);
  1436. }
  1437. break;
  1438. case REDIR_SDP:
  1439. {
  1440. uint8_t *sdp_data;
  1441. int sdp_data_size;
  1442. socklen_t len;
  1443. struct sockaddr_in my_addr;
  1444. snprintf(q, c->buffer_size,
  1445. "HTTP/1.0 200 OK\r\n"
  1446. "Content-type: application/sdp\r\n"
  1447. "\r\n");
  1448. q += strlen(q);
  1449. len = sizeof(my_addr);
  1450. /* XXX: Should probably fail? */
  1451. if (getsockname(c->fd, (struct sockaddr *)&my_addr, &len))
  1452. http_log("getsockname() failed\n");
  1453. /* XXX: should use a dynamic buffer */
  1454. sdp_data_size = prepare_sdp_description(stream,
  1455. &sdp_data,
  1456. my_addr.sin_addr);
  1457. if (sdp_data_size > 0) {
  1458. memcpy(q, sdp_data, sdp_data_size);
  1459. q += sdp_data_size;
  1460. *q = '\0';
  1461. av_free(sdp_data);
  1462. }
  1463. }
  1464. break;
  1465. default:
  1466. abort();
  1467. break;
  1468. }
  1469. /* prepare output buffer */
  1470. c->buffer_ptr = c->buffer;
  1471. c->buffer_end = q;
  1472. c->state = HTTPSTATE_SEND_HEADER;
  1473. return 0;
  1474. }
  1475. }
  1476. }
  1477. snprintf(msg, sizeof(msg), "ASX/RAM file not handled");
  1478. goto send_error;
  1479. }
  1480. stream->conns_served++;
  1481. /* XXX: add there authenticate and IP match */
  1482. if (c->post) {
  1483. /* if post, it means a feed is being sent */
  1484. if (!stream->is_feed) {
  1485. /* However it might be a status report from WMP! Let us log the
  1486. * data as it might come handy one day. */
  1487. const char *logline = 0;
  1488. int client_id = 0;
  1489. for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) {
  1490. if (av_strncasecmp(p, "Pragma: log-line=", 17) == 0) {
  1491. logline = p;
  1492. break;
  1493. }
  1494. if (av_strncasecmp(p, "Pragma: client-id=", 18) == 0)
  1495. client_id = strtol(p + 18, 0, 10);
  1496. p = strchr(p, '\n');
  1497. if (!p)
  1498. break;
  1499. p++;
  1500. }
  1501. if (logline) {
  1502. char *eol = strchr(logline, '\n');
  1503. logline += 17;
  1504. if (eol) {
  1505. if (eol[-1] == '\r')
  1506. eol--;
  1507. http_log("%.*s\n", (int) (eol - logline), logline);
  1508. c->suppress_log = 1;
  1509. }
  1510. }
  1511. #ifdef DEBUG
  1512. http_log("\nGot request:\n%s\n", c->buffer);
  1513. #endif
  1514. if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) {
  1515. HTTPContext *wmpc;
  1516. /* Now we have to find the client_id */
  1517. for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) {
  1518. if (wmpc->wmp_client_id == client_id)
  1519. break;
  1520. }
  1521. if (wmpc && modify_current_stream(wmpc, ratebuf))
  1522. wmpc->switch_pending = 1;
  1523. }
  1524. snprintf(msg, sizeof(msg), "POST command not handled");
  1525. c->stream = 0;
  1526. goto send_error;
  1527. }
  1528. if (http_start_receive_data(c) < 0) {
  1529. snprintf(msg, sizeof(msg), "could not open feed");
  1530. goto send_error;
  1531. }
  1532. c->http_error = 0;
  1533. c->state = HTTPSTATE_RECEIVE_DATA;
  1534. return 0;
  1535. }
  1536. #ifdef DEBUG
  1537. if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0)
  1538. http_log("\nGot request:\n%s\n", c->buffer);
  1539. #endif
  1540. if (c->stream->stream_type == STREAM_TYPE_STATUS)
  1541. goto send_status;
  1542. /* open input stream */
  1543. if (open_input_stream(c, info) < 0) {
  1544. snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url);
  1545. goto send_error;
  1546. }
  1547. /* prepare HTTP header */
  1548. c->buffer[0] = 0;
  1549. av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.0 200 OK\r\n");
  1550. mime_type = c->stream->fmt->mime_type;
  1551. if (!mime_type)
  1552. mime_type = "application/x-octet-stream";
  1553. av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
  1554. /* for asf, we need extra headers */
  1555. if (!strcmp(c->stream->fmt->name,"asf_stream")) {
  1556. /* Need to allocate a client id */
  1557. c->wmp_client_id = av_lfg_get(&random_state);
  1558. av_strlcatf(c->buffer, c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id);
  1559. }
  1560. av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
  1561. av_strlcatf(c->buffer, c->buffer_size, "\r\n");
  1562. q = c->buffer + strlen(c->buffer);
  1563. /* prepare output buffer */
  1564. c->http_error = 0;
  1565. c->buffer_ptr = c->buffer;
  1566. c->buffer_end = q;
  1567. c->state = HTTPSTATE_SEND_HEADER;
  1568. return 0;
  1569. send_error:
  1570. c->http_error = 404;
  1571. q = c->buffer;
  1572. if (!htmlencode(msg, &encoded_msg)) {
  1573. http_log("Could not encode filename '%s' as HTML\n", msg);
  1574. }
  1575. snprintf(q, c->buffer_size,
  1576. "HTTP/1.0 404 Not Found\r\n"
  1577. "Content-type: text/html\r\n"
  1578. "\r\n"
  1579. "<!DOCTYPE html>\n"
  1580. "<html>\n"
  1581. "<head>\n"
  1582. "<meta charset=\"UTF-8\">\n"
  1583. "<title>404 Not Found</title>\n"
  1584. "</head>\n"
  1585. "<body>%s</body>\n"
  1586. "</html>\n", encoded_msg? encoded_msg : "File not found");
  1587. q += strlen(q);
  1588. /* prepare output buffer */
  1589. c->buffer_ptr = c->buffer;
  1590. c->buffer_end = q;
  1591. c->state = HTTPSTATE_SEND_HEADER;
  1592. av_freep(&encoded_msg);
  1593. return 0;
  1594. send_status:
  1595. compute_status(c);
  1596. /* horrible: we use this value to avoid
  1597. * going to the send data state */
  1598. c->http_error = 200;
  1599. c->state = HTTPSTATE_SEND_HEADER;
  1600. return 0;
  1601. }
  1602. static void fmt_bytecount(AVIOContext *pb, int64_t count)
  1603. {
  1604. static const char suffix[] = " kMGTP";
  1605. const char *s;
  1606. for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++);
  1607. avio_printf(pb, "%"PRId64"%c", count, *s);
  1608. }
  1609. static inline void print_stream_params(AVIOContext *pb, FFServerStream *stream)
  1610. {
  1611. int i, stream_no;
  1612. const char *type = "unknown";
  1613. char parameters[64];
  1614. AVStream *st;
  1615. AVCodec *codec;
  1616. stream_no = stream->nb_streams;
  1617. avio_printf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>"
  1618. "type<th>kbit/s<th align=left>codec<th align=left>"
  1619. "Parameters\n");
  1620. for (i = 0; i < stream_no; i++) {
  1621. st = stream->streams[i];
  1622. codec = avcodec_find_encoder(st->codec->codec_id);
  1623. parameters[0] = 0;
  1624. switch(st->codec->codec_type) {
  1625. case AVMEDIA_TYPE_AUDIO:
  1626. type = "audio";
  1627. snprintf(parameters, sizeof(parameters), "%d channel(s), %d Hz",
  1628. st->codec->channels, st->codec->sample_rate);
  1629. break;
  1630. case AVMEDIA_TYPE_VIDEO:
  1631. type = "video";
  1632. snprintf(parameters, sizeof(parameters),
  1633. "%dx%d, q=%d-%d, fps=%d", st->codec->width,
  1634. st->codec->height, st->codec->qmin, st->codec->qmax,
  1635. st->codec->time_base.den / st->codec->time_base.num);
  1636. break;
  1637. default:
  1638. abort();
  1639. }
  1640. avio_printf(pb, "<tr><td align=right>%d<td>%s<td align=right>%"PRId64
  1641. "<td>%s<td>%s\n",
  1642. i, type, (int64_t)st->codec->bit_rate/1000,
  1643. codec ? codec->name : "", parameters);
  1644. }
  1645. avio_printf(pb, "</table>\n");
  1646. }
  1647. static void compute_status(HTTPContext *c)
  1648. {
  1649. HTTPContext *c1;
  1650. FFServerStream *stream;
  1651. char *p;
  1652. time_t ti;
  1653. int i, len;
  1654. AVIOContext *pb;
  1655. if (avio_open_dyn_buf(&pb) < 0) {
  1656. /* XXX: return an error ? */
  1657. c->buffer_ptr = c->buffer;
  1658. c->buffer_end = c->buffer;
  1659. return;
  1660. }
  1661. avio_printf(pb, "HTTP/1.0 200 OK\r\n");
  1662. avio_printf(pb, "Content-type: text/html\r\n");
  1663. avio_printf(pb, "Pragma: no-cache\r\n");
  1664. avio_printf(pb, "\r\n");
  1665. avio_printf(pb, "<!DOCTYPE html>\n");
  1666. avio_printf(pb, "<html><head><title>%s Status</title>\n", program_name);
  1667. if (c->stream->feed_filename[0])
  1668. avio_printf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n",
  1669. c->stream->feed_filename);
  1670. avio_printf(pb, "</head>\n<body>");
  1671. avio_printf(pb, "<h1>%s Status</h1>\n", program_name);
  1672. /* format status */
  1673. avio_printf(pb, "<h2>Available Streams</h2>\n");
  1674. avio_printf(pb, "<table cellspacing=0 cellpadding=4>\n");
  1675. avio_printf(pb, "<tr><th valign=top>Path<th align=left>Served<br>Conns<th><br>bytes<th valign=top>Format<th>Bit rate<br>kbit/s<th align=left>Video<br>kbit/s<th><br>Codec<th align=left>Audio<br>kbit/s<th><br>Codec<th align=left valign=top>Feed\n");
  1676. stream = config.first_stream;
  1677. while (stream) {
  1678. char sfilename[1024];
  1679. char *eosf;
  1680. if (stream->feed == stream) {
  1681. stream = stream->next;
  1682. continue;
  1683. }
  1684. av_strlcpy(sfilename, stream->filename, sizeof(sfilename) - 10);
  1685. eosf = sfilename + strlen(sfilename);
  1686. if (eosf - sfilename >= 4) {
  1687. if (strcmp(eosf - 4, ".asf") == 0)
  1688. strcpy(eosf - 4, ".asx");
  1689. else if (strcmp(eosf - 3, ".rm") == 0)
  1690. strcpy(eosf - 3, ".ram");
  1691. else if (stream->fmt && !strcmp(stream->fmt->name, "rtp")) {
  1692. /* generate a sample RTSP director if
  1693. * unicast. Generate an SDP redirector if
  1694. * multicast */
  1695. eosf = strrchr(sfilename, '.');
  1696. if (!eosf)
  1697. eosf = sfilename + strlen(sfilename);
  1698. if (stream->is_multicast)
  1699. strcpy(eosf, ".sdp");
  1700. else
  1701. strcpy(eosf, ".rtsp");
  1702. }
  1703. }
  1704. avio_printf(pb, "<tr><td><a href=\"/%s\">%s</a> ",
  1705. sfilename, stream->filename);
  1706. avio_printf(pb, "<td align=right> %d <td align=right> ",
  1707. stream->conns_served);
  1708. fmt_bytecount(pb, stream->bytes_served);
  1709. switch(stream->stream_type) {
  1710. case STREAM_TYPE_LIVE: {
  1711. int audio_bit_rate = 0;
  1712. int video_bit_rate = 0;
  1713. const char *audio_codec_name = "";
  1714. const char *video_codec_name = "";
  1715. const char *audio_codec_name_extra = "";
  1716. const char *video_codec_name_extra = "";
  1717. for(i=0;i<stream->nb_streams;i++) {
  1718. AVStream *st = stream->streams[i];
  1719. AVCodec *codec = avcodec_find_encoder(st->codec->codec_id);
  1720. switch(st->codec->codec_type) {
  1721. case AVMEDIA_TYPE_AUDIO:
  1722. audio_bit_rate += st->codec->bit_rate;
  1723. if (codec) {
  1724. if (*audio_codec_name)
  1725. audio_codec_name_extra = "...";
  1726. audio_codec_name = codec->name;
  1727. }
  1728. break;
  1729. case AVMEDIA_TYPE_VIDEO:
  1730. video_bit_rate += st->codec->bit_rate;
  1731. if (codec) {
  1732. if (*video_codec_name)
  1733. video_codec_name_extra = "...";
  1734. video_codec_name = codec->name;
  1735. }
  1736. break;
  1737. case AVMEDIA_TYPE_DATA:
  1738. video_bit_rate += st->codec->bit_rate;
  1739. break;
  1740. default:
  1741. abort();
  1742. }
  1743. }
  1744. avio_printf(pb, "<td align=center> %s <td align=right> %d "
  1745. "<td align=right> %d <td> %s %s <td align=right> "
  1746. "%d <td> %s %s",
  1747. stream->fmt->name, stream->bandwidth,
  1748. video_bit_rate / 1000, video_codec_name,
  1749. video_codec_name_extra, audio_bit_rate / 1000,
  1750. audio_codec_name, audio_codec_name_extra);
  1751. if (stream->feed)
  1752. avio_printf(pb, "<td>%s", stream->feed->filename);
  1753. else
  1754. avio_printf(pb, "<td>%s", stream->feed_filename);
  1755. avio_printf(pb, "\n");
  1756. }
  1757. break;
  1758. default:
  1759. avio_printf(pb, "<td align=center> - <td align=right> - "
  1760. "<td align=right> - <td><td align=right> - <td>\n");
  1761. break;
  1762. }
  1763. stream = stream->next;
  1764. }
  1765. avio_printf(pb, "</table>\n");
  1766. stream = config.first_stream;
  1767. while (stream) {
  1768. if (stream->feed != stream) {
  1769. stream = stream->next;
  1770. continue;
  1771. }
  1772. avio_printf(pb, "<h2>Feed %s</h2>", stream->filename);
  1773. if (stream->pid) {
  1774. avio_printf(pb, "Running as pid %"PRId64".\n", (int64_t) stream->pid);
  1775. #if defined(linux)
  1776. {
  1777. FILE *pid_stat;
  1778. char ps_cmd[64];
  1779. /* This is somewhat linux specific I guess */
  1780. snprintf(ps_cmd, sizeof(ps_cmd),
  1781. "ps -o \"%%cpu,cputime\" --no-headers %"PRId64"",
  1782. (int64_t) stream->pid);
  1783. pid_stat = popen(ps_cmd, "r");
  1784. if (pid_stat) {
  1785. char cpuperc[10];
  1786. char cpuused[64];
  1787. if (fscanf(pid_stat, "%9s %63s", cpuperc, cpuused) == 2) {
  1788. avio_printf(pb, "Currently using %s%% of the cpu. "
  1789. "Total time used %s.\n",
  1790. cpuperc, cpuused);
  1791. }
  1792. fclose(pid_stat);
  1793. }
  1794. }
  1795. #endif
  1796. avio_printf(pb, "<p>");
  1797. }
  1798. print_stream_params(pb, stream);
  1799. stream = stream->next;
  1800. }
  1801. /* connection status */
  1802. avio_printf(pb, "<h2>Connection Status</h2>\n");
  1803. avio_printf(pb, "Number of connections: %d / %d<br>\n",
  1804. nb_connections, config.nb_max_connections);
  1805. avio_printf(pb, "Bandwidth in use: %"PRIu64"k / %"PRIu64"k<br>\n",
  1806. current_bandwidth, config.max_bandwidth);
  1807. avio_printf(pb, "<table>\n");
  1808. avio_printf(pb, "<tr><th>#<th>File<th>IP<th>Proto<th>State<th>Target "
  1809. "bit/s<th>Actual bit/s<th>Bytes transferred\n");
  1810. c1 = first_http_ctx;
  1811. i = 0;
  1812. while (c1) {
  1813. int bitrate;
  1814. int j;
  1815. bitrate = 0;
  1816. if (c1->stream) {
  1817. for (j = 0; j < c1->stream->nb_streams; j++) {
  1818. if (!c1->stream->feed)
  1819. bitrate += c1->stream->streams[j]->codec->bit_rate;
  1820. else if (c1->feed_streams[j] >= 0)
  1821. bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec->bit_rate;
  1822. }
  1823. }
  1824. i++;
  1825. p = inet_ntoa(c1->from_addr.sin_addr);
  1826. avio_printf(pb, "<tr><td><b>%d</b><td>%s%s<td>%s<td>%s<td>%s"
  1827. "<td align=right>",
  1828. i, c1->stream ? c1->stream->filename : "",
  1829. c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p,
  1830. c1->protocol, http_state[c1->state]);
  1831. fmt_bytecount(pb, bitrate);
  1832. avio_printf(pb, "<td align=right>");
  1833. fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8);
  1834. avio_printf(pb, "<td align=right>");
  1835. fmt_bytecount(pb, c1->data_count);
  1836. avio_printf(pb, "\n");
  1837. c1 = c1->next;
  1838. }
  1839. avio_printf(pb, "</table>\n");
  1840. /* date */
  1841. ti = time(NULL);
  1842. p = ctime(&ti);
  1843. avio_printf(pb, "<hr size=1 noshade>Generated at %s", p);
  1844. avio_printf(pb, "</body>\n</html>\n");
  1845. len = avio_close_dyn_buf(pb, &c->pb_buffer);
  1846. c->buffer_ptr = c->pb_buffer;
  1847. c->buffer_end = c->pb_buffer + len;
  1848. }
  1849. static int open_input_stream(HTTPContext *c, const char *info)
  1850. {
  1851. char buf[128];
  1852. char input_filename[1024];
  1853. AVFormatContext *s = NULL;
  1854. int buf_size, i, ret;
  1855. int64_t stream_pos;
  1856. /* find file name */
  1857. if (c->stream->feed) {
  1858. strcpy(input_filename, c->stream->feed->feed_filename);
  1859. buf_size = FFM_PACKET_SIZE;
  1860. /* compute position (absolute time) */
  1861. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1862. if ((ret = av_parse_time(&stream_pos, buf, 0)) < 0) {
  1863. http_log("Invalid date specification '%s' for stream\n", buf);
  1864. return ret;
  1865. }
  1866. } else if (av_find_info_tag(buf, sizeof(buf), "buffer", info)) {
  1867. int prebuffer = strtol(buf, 0, 10);
  1868. stream_pos = av_gettime() - prebuffer * (int64_t)1000000;
  1869. } else
  1870. stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;
  1871. } else {
  1872. strcpy(input_filename, c->stream->feed_filename);
  1873. buf_size = 0;
  1874. /* compute position (relative time) */
  1875. if (av_find_info_tag(buf, sizeof(buf), "date", info)) {
  1876. if ((ret = av_parse_time(&stream_pos, buf, 1)) < 0) {
  1877. http_log("Invalid date specification '%s' for stream\n", buf);
  1878. return ret;
  1879. }
  1880. } else
  1881. stream_pos = 0;
  1882. }
  1883. if (!input_filename[0]) {
  1884. http_log("No filename was specified for stream\n");
  1885. return AVERROR(EINVAL);
  1886. }
  1887. /* open stream */
  1888. ret = avformat_open_input(&s, input_filename, c->stream->ifmt,
  1889. &c->stream->in_opts);
  1890. if (ret < 0) {
  1891. http_log("Could not open input '%s': %s\n",
  1892. input_filename, av_err2str(ret));
  1893. return ret;
  1894. }
  1895. /* set buffer size */
  1896. if (buf_size > 0) {
  1897. ret = ffio_set_buf_size(s->pb, buf_size);
  1898. if (ret < 0) {
  1899. http_log("Failed to set buffer size\n");
  1900. return ret;
  1901. }
  1902. }
  1903. s->flags |= AVFMT_FLAG_GENPTS;
  1904. c->fmt_in = s;
  1905. if (strcmp(s->iformat->name, "ffm") &&
  1906. (ret = avformat_find_stream_info(c->fmt_in, NULL)) < 0) {
  1907. http_log("Could not find stream info for input '%s'\n", input_filename);
  1908. avformat_close_input(&s);
  1909. return ret;
  1910. }
  1911. /* choose stream as clock source (we favor the video stream if
  1912. * present) for packet sending */
  1913. c->pts_stream_index = 0;
  1914. for(i=0;i<c->stream->nb_streams;i++) {
  1915. if (c->pts_stream_index == 0 &&
  1916. c->stream->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1917. c->pts_stream_index = i;
  1918. }
  1919. }
  1920. if (c->fmt_in->iformat->read_seek)
  1921. av_seek_frame(c->fmt_in, -1, stream_pos, 0);
  1922. /* set the start time (needed for maxtime and RTP packet timing) */
  1923. c->start_time = cur_time;
  1924. c->first_pts = AV_NOPTS_VALUE;
  1925. return 0;
  1926. }
  1927. /* return the server clock (in us) */
  1928. static int64_t get_server_clock(HTTPContext *c)
  1929. {
  1930. /* compute current pts value from system time */
  1931. return (cur_time - c->start_time) * 1000;
  1932. }
  1933. /* return the estimated time (in us) at which the current packet must be sent */
  1934. static int64_t get_packet_send_clock(HTTPContext *c)
  1935. {
  1936. int bytes_left, bytes_sent, frame_bytes;
  1937. frame_bytes = c->cur_frame_bytes;
  1938. if (frame_bytes <= 0)
  1939. return c->cur_pts;
  1940. bytes_left = c->buffer_end - c->buffer_ptr;
  1941. bytes_sent = frame_bytes - bytes_left;
  1942. return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes;
  1943. }
  1944. static int http_prepare_data(HTTPContext *c)
  1945. {
  1946. int i, len, ret;
  1947. AVFormatContext *ctx;
  1948. av_freep(&c->pb_buffer);
  1949. switch(c->state) {
  1950. case HTTPSTATE_SEND_DATA_HEADER:
  1951. ctx = avformat_alloc_context();
  1952. if (!ctx)
  1953. return AVERROR(ENOMEM);
  1954. c->fmt_ctx = *ctx;
  1955. av_freep(&ctx);
  1956. av_dict_copy(&(c->fmt_ctx.metadata), c->stream->metadata, 0);
  1957. c->fmt_ctx.streams = av_mallocz_array(c->stream->nb_streams,
  1958. sizeof(AVStream *));
  1959. if (!c->fmt_ctx.streams)
  1960. return AVERROR(ENOMEM);
  1961. for(i=0;i<c->stream->nb_streams;i++) {
  1962. AVStream *src;
  1963. c->fmt_ctx.streams[i] = av_mallocz(sizeof(AVStream));
  1964. /* if file or feed, then just take streams from FFServerStream
  1965. * struct */
  1966. if (!c->stream->feed ||
  1967. c->stream->feed == c->stream)
  1968. src = c->stream->streams[i];
  1969. else
  1970. src = c->stream->feed->streams[c->stream->feed_streams[i]];
  1971. *(c->fmt_ctx.streams[i]) = *src;
  1972. c->fmt_ctx.streams[i]->priv_data = 0;
  1973. /* XXX: should be done in AVStream, not in codec */
  1974. c->fmt_ctx.streams[i]->codec->frame_number = 0;
  1975. }
  1976. /* set output format parameters */
  1977. c->fmt_ctx.oformat = c->stream->fmt;
  1978. c->fmt_ctx.nb_streams = c->stream->nb_streams;
  1979. c->got_key_frame = 0;
  1980. /* prepare header and save header data in a stream */
  1981. if (avio_open_dyn_buf(&c->fmt_ctx.pb) < 0) {
  1982. /* XXX: potential leak */
  1983. return -1;
  1984. }
  1985. c->fmt_ctx.pb->seekable = 0;
  1986. /*
  1987. * HACK to avoid MPEG-PS muxer to spit many underflow errors
  1988. * Default value from FFmpeg
  1989. * Try to set it using configuration option
  1990. */
  1991. c->fmt_ctx.max_delay = (int)(0.7*AV_TIME_BASE);
  1992. if ((ret = avformat_write_header(&c->fmt_ctx, NULL)) < 0) {
  1993. http_log("Error writing output header for stream '%s': %s\n",
  1994. c->stream->filename, av_err2str(ret));
  1995. return ret;
  1996. }
  1997. av_dict_free(&c->fmt_ctx.metadata);
  1998. len = avio_close_dyn_buf(c->fmt_ctx.pb, &c->pb_buffer);
  1999. c->buffer_ptr = c->pb_buffer;
  2000. c->buffer_end = c->pb_buffer + len;
  2001. c->state = HTTPSTATE_SEND_DATA;
  2002. c->last_packet_sent = 0;
  2003. break;
  2004. case HTTPSTATE_SEND_DATA:
  2005. /* find a new packet */
  2006. /* read a packet from the input stream */
  2007. if (c->stream->feed)
  2008. ffm_set_write_index(c->fmt_in,
  2009. c->stream->feed->feed_write_index,
  2010. c->stream->feed->feed_size);
  2011. if (c->stream->max_time &&
  2012. c->stream->max_time + c->start_time - cur_time < 0)
  2013. /* We have timed out */
  2014. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2015. else {
  2016. AVPacket pkt;
  2017. redo:
  2018. ret = av_read_frame(c->fmt_in, &pkt);
  2019. if (ret < 0) {
  2020. if (c->stream->feed) {
  2021. /* if coming from feed, it means we reached the end of the
  2022. * ffm file, so must wait for more data */
  2023. c->state = HTTPSTATE_WAIT_FEED;
  2024. return 1; /* state changed */
  2025. }
  2026. if (ret == AVERROR(EAGAIN)) {
  2027. /* input not ready, come back later */
  2028. return 0;
  2029. }
  2030. if (c->stream->loop) {
  2031. avformat_close_input(&c->fmt_in);
  2032. if (open_input_stream(c, "") < 0)
  2033. goto no_loop;
  2034. goto redo;
  2035. } else {
  2036. no_loop:
  2037. /* must send trailer now because EOF or error */
  2038. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2039. }
  2040. } else {
  2041. int source_index = pkt.stream_index;
  2042. /* update first pts if needed */
  2043. if (c->first_pts == AV_NOPTS_VALUE && pkt.dts != AV_NOPTS_VALUE) {
  2044. c->first_pts = av_rescale_q(pkt.dts, c->fmt_in->streams[pkt.stream_index]->time_base, AV_TIME_BASE_Q);
  2045. c->start_time = cur_time;
  2046. }
  2047. /* send it to the appropriate stream */
  2048. if (c->stream->feed) {
  2049. /* if coming from a feed, select the right stream */
  2050. if (c->switch_pending) {
  2051. c->switch_pending = 0;
  2052. for(i=0;i<c->stream->nb_streams;i++) {
  2053. if (c->switch_feed_streams[i] == pkt.stream_index)
  2054. if (pkt.flags & AV_PKT_FLAG_KEY)
  2055. c->switch_feed_streams[i] = -1;
  2056. if (c->switch_feed_streams[i] >= 0)
  2057. c->switch_pending = 1;
  2058. }
  2059. }
  2060. for(i=0;i<c->stream->nb_streams;i++) {
  2061. if (c->stream->feed_streams[i] == pkt.stream_index) {
  2062. AVStream *st = c->fmt_in->streams[source_index];
  2063. pkt.stream_index = i;
  2064. if (pkt.flags & AV_PKT_FLAG_KEY &&
  2065. (st->codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  2066. c->stream->nb_streams == 1))
  2067. c->got_key_frame = 1;
  2068. if (!c->stream->send_on_key || c->got_key_frame)
  2069. goto send_it;
  2070. }
  2071. }
  2072. } else {
  2073. AVCodecContext *codec;
  2074. AVStream *ist, *ost;
  2075. send_it:
  2076. ist = c->fmt_in->streams[source_index];
  2077. /* specific handling for RTP: we use several
  2078. * output streams (one for each RTP connection).
  2079. * XXX: need more abstract handling */
  2080. if (c->is_packetized) {
  2081. /* compute send time and duration */
  2082. if (pkt.dts != AV_NOPTS_VALUE) {
  2083. c->cur_pts = av_rescale_q(pkt.dts, ist->time_base, AV_TIME_BASE_Q);
  2084. c->cur_pts -= c->first_pts;
  2085. }
  2086. c->cur_frame_duration = av_rescale_q(pkt.duration, ist->time_base, AV_TIME_BASE_Q);
  2087. /* find RTP context */
  2088. c->packet_stream_index = pkt.stream_index;
  2089. ctx = c->rtp_ctx[c->packet_stream_index];
  2090. if(!ctx) {
  2091. av_packet_unref(&pkt);
  2092. break;
  2093. }
  2094. codec = ctx->streams[0]->codec;
  2095. /* only one stream per RTP connection */
  2096. pkt.stream_index = 0;
  2097. } else {
  2098. ctx = &c->fmt_ctx;
  2099. /* Fudge here */
  2100. codec = ctx->streams[pkt.stream_index]->codec;
  2101. }
  2102. if (c->is_packetized) {
  2103. int max_packet_size;
  2104. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP)
  2105. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  2106. else
  2107. max_packet_size = c->rtp_handles[c->packet_stream_index]->max_packet_size;
  2108. ret = ffio_open_dyn_packet_buf(&ctx->pb,
  2109. max_packet_size);
  2110. } else
  2111. ret = avio_open_dyn_buf(&ctx->pb);
  2112. if (ret < 0) {
  2113. /* XXX: potential leak */
  2114. return -1;
  2115. }
  2116. ost = ctx->streams[pkt.stream_index];
  2117. ctx->pb->seekable = 0;
  2118. if (pkt.dts != AV_NOPTS_VALUE)
  2119. pkt.dts = av_rescale_q(pkt.dts, ist->time_base,
  2120. ost->time_base);
  2121. if (pkt.pts != AV_NOPTS_VALUE)
  2122. pkt.pts = av_rescale_q(pkt.pts, ist->time_base,
  2123. ost->time_base);
  2124. pkt.duration = av_rescale_q(pkt.duration, ist->time_base,
  2125. ost->time_base);
  2126. if ((ret = av_write_frame(ctx, &pkt)) < 0) {
  2127. http_log("Error writing frame to output for stream '%s': %s\n",
  2128. c->stream->filename, av_err2str(ret));
  2129. c->state = HTTPSTATE_SEND_DATA_TRAILER;
  2130. }
  2131. av_freep(&c->pb_buffer);
  2132. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2133. ctx->pb = NULL;
  2134. c->cur_frame_bytes = len;
  2135. c->buffer_ptr = c->pb_buffer;
  2136. c->buffer_end = c->pb_buffer + len;
  2137. codec->frame_number++;
  2138. if (len == 0) {
  2139. av_packet_unref(&pkt);
  2140. goto redo;
  2141. }
  2142. }
  2143. av_packet_unref(&pkt);
  2144. }
  2145. }
  2146. break;
  2147. default:
  2148. case HTTPSTATE_SEND_DATA_TRAILER:
  2149. /* last packet test ? */
  2150. if (c->last_packet_sent || c->is_packetized)
  2151. return -1;
  2152. ctx = &c->fmt_ctx;
  2153. /* prepare header */
  2154. if (avio_open_dyn_buf(&ctx->pb) < 0) {
  2155. /* XXX: potential leak */
  2156. return -1;
  2157. }
  2158. c->fmt_ctx.pb->seekable = 0;
  2159. av_write_trailer(ctx);
  2160. len = avio_close_dyn_buf(ctx->pb, &c->pb_buffer);
  2161. c->buffer_ptr = c->pb_buffer;
  2162. c->buffer_end = c->pb_buffer + len;
  2163. c->last_packet_sent = 1;
  2164. break;
  2165. }
  2166. return 0;
  2167. }
  2168. /* should convert the format at the same time */
  2169. /* send data starting at c->buffer_ptr to the output connection
  2170. * (either UDP or TCP)
  2171. */
  2172. static int http_send_data(HTTPContext *c)
  2173. {
  2174. int len, ret;
  2175. for(;;) {
  2176. if (c->buffer_ptr >= c->buffer_end) {
  2177. ret = http_prepare_data(c);
  2178. if (ret < 0)
  2179. return -1;
  2180. else if (ret)
  2181. /* state change requested */
  2182. break;
  2183. } else {
  2184. if (c->is_packetized) {
  2185. /* RTP data output */
  2186. len = c->buffer_end - c->buffer_ptr;
  2187. if (len < 4) {
  2188. /* fail safe - should never happen */
  2189. fail1:
  2190. c->buffer_ptr = c->buffer_end;
  2191. return 0;
  2192. }
  2193. len = (c->buffer_ptr[0] << 24) |
  2194. (c->buffer_ptr[1] << 16) |
  2195. (c->buffer_ptr[2] << 8) |
  2196. (c->buffer_ptr[3]);
  2197. if (len > (c->buffer_end - c->buffer_ptr))
  2198. goto fail1;
  2199. if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) {
  2200. /* nothing to send yet: we can wait */
  2201. return 0;
  2202. }
  2203. c->data_count += len;
  2204. update_datarate(&c->datarate, c->data_count);
  2205. if (c->stream)
  2206. c->stream->bytes_served += len;
  2207. if (c->rtp_protocol == RTSP_LOWER_TRANSPORT_TCP) {
  2208. /* RTP packets are sent inside the RTSP TCP connection */
  2209. AVIOContext *pb;
  2210. int interleaved_index, size;
  2211. uint8_t header[4];
  2212. HTTPContext *rtsp_c;
  2213. rtsp_c = c->rtsp_c;
  2214. /* if no RTSP connection left, error */
  2215. if (!rtsp_c)
  2216. return -1;
  2217. /* if already sending something, then wait. */
  2218. if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST)
  2219. break;
  2220. if (avio_open_dyn_buf(&pb) < 0)
  2221. goto fail1;
  2222. interleaved_index = c->packet_stream_index * 2;
  2223. /* RTCP packets are sent at odd indexes */
  2224. if (c->buffer_ptr[1] == 200)
  2225. interleaved_index++;
  2226. /* write RTSP TCP header */
  2227. header[0] = '$';
  2228. header[1] = interleaved_index;
  2229. header[2] = len >> 8;
  2230. header[3] = len;
  2231. avio_write(pb, header, 4);
  2232. /* write RTP packet data */
  2233. c->buffer_ptr += 4;
  2234. avio_write(pb, c->buffer_ptr, len);
  2235. size = avio_close_dyn_buf(pb, &c->packet_buffer);
  2236. /* prepare asynchronous TCP sending */
  2237. rtsp_c->packet_buffer_ptr = c->packet_buffer;
  2238. rtsp_c->packet_buffer_end = c->packet_buffer + size;
  2239. c->buffer_ptr += len;
  2240. /* send everything we can NOW */
  2241. len = send(rtsp_c->fd, rtsp_c->packet_buffer_ptr,
  2242. rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr, 0);
  2243. if (len > 0)
  2244. rtsp_c->packet_buffer_ptr += len;
  2245. if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) {
  2246. /* if we could not send all the data, we will
  2247. * send it later, so a new state is needed to
  2248. * "lock" the RTSP TCP connection */
  2249. rtsp_c->state = RTSPSTATE_SEND_PACKET;
  2250. break;
  2251. } else
  2252. /* all data has been sent */
  2253. av_freep(&c->packet_buffer);
  2254. } else {
  2255. /* send RTP packet directly in UDP */
  2256. c->buffer_ptr += 4;
  2257. ffurl_write(c->rtp_handles[c->packet_stream_index],
  2258. c->buffer_ptr, len);
  2259. c->buffer_ptr += len;
  2260. /* here we continue as we can send several packets
  2261. * per 10 ms slot */
  2262. }
  2263. } else {
  2264. /* TCP data output */
  2265. len = send(c->fd, c->buffer_ptr,
  2266. c->buffer_end - c->buffer_ptr, 0);
  2267. if (len < 0) {
  2268. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2269. ff_neterrno() != AVERROR(EINTR))
  2270. /* error : close connection */
  2271. return -1;
  2272. else
  2273. return 0;
  2274. }
  2275. c->buffer_ptr += len;
  2276. c->data_count += len;
  2277. update_datarate(&c->datarate, c->data_count);
  2278. if (c->stream)
  2279. c->stream->bytes_served += len;
  2280. break;
  2281. }
  2282. }
  2283. } /* for(;;) */
  2284. return 0;
  2285. }
  2286. static int http_start_receive_data(HTTPContext *c)
  2287. {
  2288. int fd;
  2289. int ret;
  2290. int64_t ret64;
  2291. if (c->stream->feed_opened) {
  2292. http_log("Stream feed '%s' was not opened\n",
  2293. c->stream->feed_filename);
  2294. return AVERROR(EINVAL);
  2295. }
  2296. /* Don't permit writing to this one */
  2297. if (c->stream->readonly) {
  2298. http_log("Cannot write to read-only file '%s'\n",
  2299. c->stream->feed_filename);
  2300. return AVERROR(EINVAL);
  2301. }
  2302. /* open feed */
  2303. fd = open(c->stream->feed_filename, O_RDWR);
  2304. if (fd < 0) {
  2305. ret = AVERROR(errno);
  2306. http_log("Could not open feed file '%s': %s\n",
  2307. c->stream->feed_filename, strerror(errno));
  2308. return ret;
  2309. }
  2310. c->feed_fd = fd;
  2311. if (c->stream->truncate) {
  2312. /* truncate feed file */
  2313. ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
  2314. http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
  2315. if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
  2316. ret = AVERROR(errno);
  2317. http_log("Error truncating feed file '%s': %s\n",
  2318. c->stream->feed_filename, strerror(errno));
  2319. return ret;
  2320. }
  2321. } else {
  2322. ret64 = ffm_read_write_index(fd);
  2323. if (ret64 < 0) {
  2324. http_log("Error reading write index from feed file '%s': %s\n",
  2325. c->stream->feed_filename, strerror(errno));
  2326. return ret64;
  2327. }
  2328. c->stream->feed_write_index = ret64;
  2329. }
  2330. c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
  2331. FFM_PACKET_SIZE);
  2332. c->stream->feed_size = lseek(fd, 0, SEEK_END);
  2333. lseek(fd, 0, SEEK_SET);
  2334. /* init buffer input */
  2335. c->buffer_ptr = c->buffer;
  2336. c->buffer_end = c->buffer + FFM_PACKET_SIZE;
  2337. c->stream->feed_opened = 1;
  2338. c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
  2339. return 0;
  2340. }
  2341. static int http_receive_data(HTTPContext *c)
  2342. {
  2343. HTTPContext *c1;
  2344. int len, loop_run = 0;
  2345. while (c->chunked_encoding && !c->chunk_size &&
  2346. c->buffer_end > c->buffer_ptr) {
  2347. /* read chunk header, if present */
  2348. len = recv(c->fd, c->buffer_ptr, 1, 0);
  2349. if (len < 0) {
  2350. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2351. ff_neterrno() != AVERROR(EINTR))
  2352. /* error : close connection */
  2353. goto fail;
  2354. return 0;
  2355. } else if (len == 0) {
  2356. /* end of connection : close it */
  2357. goto fail;
  2358. } else if (c->buffer_ptr - c->buffer >= 2 &&
  2359. !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
  2360. c->chunk_size = strtol(c->buffer, 0, 16);
  2361. if (c->chunk_size <= 0) { // end of stream or invalid chunk size
  2362. c->chunk_size = 0;
  2363. goto fail;
  2364. }
  2365. c->buffer_ptr = c->buffer;
  2366. break;
  2367. } else if (++loop_run > 10)
  2368. /* no chunk header, abort */
  2369. goto fail;
  2370. else
  2371. c->buffer_ptr++;
  2372. }
  2373. if (c->buffer_end > c->buffer_ptr) {
  2374. len = recv(c->fd, c->buffer_ptr,
  2375. FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
  2376. if (len < 0) {
  2377. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2378. ff_neterrno() != AVERROR(EINTR))
  2379. /* error : close connection */
  2380. goto fail;
  2381. } else if (len == 0)
  2382. /* end of connection : close it */
  2383. goto fail;
  2384. else {
  2385. av_assert0(len <= c->chunk_size);
  2386. c->chunk_size -= len;
  2387. c->buffer_ptr += len;
  2388. c->data_count += len;
  2389. update_datarate(&c->datarate, c->data_count);
  2390. }
  2391. }
  2392. if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
  2393. if (c->buffer[0] != 'f' ||
  2394. c->buffer[1] != 'm') {
  2395. http_log("Feed stream has become desynchronized -- disconnecting\n");
  2396. goto fail;
  2397. }
  2398. }
  2399. if (c->buffer_ptr >= c->buffer_end) {
  2400. FFServerStream *feed = c->stream;
  2401. /* a packet has been received : write it in the store, except
  2402. * if header */
  2403. if (c->data_count > FFM_PACKET_SIZE) {
  2404. /* XXX: use llseek or url_seek
  2405. * XXX: Should probably fail? */
  2406. if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
  2407. http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
  2408. if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
  2409. http_log("Error writing to feed file: %s\n", strerror(errno));
  2410. goto fail;
  2411. }
  2412. feed->feed_write_index += FFM_PACKET_SIZE;
  2413. /* update file size */
  2414. if (feed->feed_write_index > c->stream->feed_size)
  2415. feed->feed_size = feed->feed_write_index;
  2416. /* handle wrap around if max file size reached */
  2417. if (c->stream->feed_max_size &&
  2418. feed->feed_write_index >= c->stream->feed_max_size)
  2419. feed->feed_write_index = FFM_PACKET_SIZE;
  2420. /* write index */
  2421. if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
  2422. http_log("Error writing index to feed file: %s\n",
  2423. strerror(errno));
  2424. goto fail;
  2425. }
  2426. /* wake up any waiting connections */
  2427. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2428. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2429. c1->stream->feed == c->stream->feed)
  2430. c1->state = HTTPSTATE_SEND_DATA;
  2431. }
  2432. } else {
  2433. /* We have a header in our hands that contains useful data */
  2434. AVFormatContext *s = avformat_alloc_context();
  2435. AVIOContext *pb;
  2436. AVInputFormat *fmt_in;
  2437. int i;
  2438. if (!s)
  2439. goto fail;
  2440. /* use feed output format name to find corresponding input format */
  2441. fmt_in = av_find_input_format(feed->fmt->name);
  2442. if (!fmt_in)
  2443. goto fail;
  2444. pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
  2445. 0, NULL, NULL, NULL, NULL);
  2446. if (!pb)
  2447. goto fail;
  2448. pb->seekable = 0;
  2449. s->pb = pb;
  2450. if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
  2451. av_freep(&pb);
  2452. goto fail;
  2453. }
  2454. /* Now we have the actual streams */
  2455. if (s->nb_streams != feed->nb_streams) {
  2456. avformat_close_input(&s);
  2457. av_freep(&pb);
  2458. http_log("Feed '%s' stream number does not match registered feed\n",
  2459. c->stream->feed_filename);
  2460. goto fail;
  2461. }
  2462. for (i = 0; i < s->nb_streams; i++) {
  2463. AVStream *fst = feed->streams[i];
  2464. AVStream *st = s->streams[i];
  2465. avcodec_copy_context(fst->codec, st->codec);
  2466. }
  2467. avformat_close_input(&s);
  2468. av_freep(&pb);
  2469. }
  2470. c->buffer_ptr = c->buffer;
  2471. }
  2472. return 0;
  2473. fail:
  2474. c->stream->feed_opened = 0;
  2475. close(c->feed_fd);
  2476. /* wake up any waiting connections to stop waiting for feed */
  2477. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2478. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2479. c1->stream->feed == c->stream->feed)
  2480. c1->state = HTTPSTATE_SEND_DATA_TRAILER;
  2481. }
  2482. return -1;
  2483. }
  2484. /********************************************************************/
  2485. /* RTSP handling */
  2486. static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
  2487. {
  2488. const char *str;
  2489. time_t ti;
  2490. struct tm *tm;
  2491. char buf2[32];
  2492. str = RTSP_STATUS_CODE2STRING(error_number);
  2493. if (!str)
  2494. str = "Unknown Error";
  2495. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
  2496. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2497. /* output GMT time */
  2498. ti = time(NULL);
  2499. tm = gmtime(&ti);
  2500. strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
  2501. avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
  2502. }
  2503. static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
  2504. {
  2505. rtsp_reply_header(c, error_number);
  2506. avio_printf(c->pb, "\r\n");
  2507. }
  2508. static int rtsp_parse_request(HTTPContext *c)
  2509. {
  2510. const char *p, *p1, *p2;
  2511. char cmd[32];
  2512. char url[1024];
  2513. char protocol[32];
  2514. char line[1024];
  2515. int len;
  2516. RTSPMessageHeader header1 = { 0 }, *header = &header1;
  2517. c->buffer_ptr[0] = '\0';
  2518. p = c->buffer;
  2519. get_word(cmd, sizeof(cmd), &p);
  2520. get_word(url, sizeof(url), &p);
  2521. get_word(protocol, sizeof(protocol), &p);
  2522. av_strlcpy(c->method, cmd, sizeof(c->method));
  2523. av_strlcpy(c->url, url, sizeof(c->url));
  2524. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  2525. if (avio_open_dyn_buf(&c->pb) < 0) {
  2526. /* XXX: cannot do more */
  2527. c->pb = NULL; /* safety */
  2528. return -1;
  2529. }
  2530. /* check version name */
  2531. if (strcmp(protocol, "RTSP/1.0")) {
  2532. rtsp_reply_error(c, RTSP_STATUS_VERSION);
  2533. goto the_end;
  2534. }
  2535. /* parse each header line */
  2536. /* skip to next line */
  2537. while (*p != '\n' && *p != '\0')
  2538. p++;
  2539. if (*p == '\n')
  2540. p++;
  2541. while (*p != '\0') {
  2542. p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
  2543. if (!p1)
  2544. break;
  2545. p2 = p1;
  2546. if (p2 > p && p2[-1] == '\r')
  2547. p2--;
  2548. /* skip empty line */
  2549. if (p2 == p)
  2550. break;
  2551. len = p2 - p;
  2552. if (len > sizeof(line) - 1)
  2553. len = sizeof(line) - 1;
  2554. memcpy(line, p, len);
  2555. line[len] = '\0';
  2556. ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
  2557. p = p1 + 1;
  2558. }
  2559. /* handle sequence number */
  2560. c->seq = header->seq;
  2561. if (!strcmp(cmd, "DESCRIBE"))
  2562. rtsp_cmd_describe(c, url);
  2563. else if (!strcmp(cmd, "OPTIONS"))
  2564. rtsp_cmd_options(c, url);
  2565. else if (!strcmp(cmd, "SETUP"))
  2566. rtsp_cmd_setup(c, url, header);
  2567. else if (!strcmp(cmd, "PLAY"))
  2568. rtsp_cmd_play(c, url, header);
  2569. else if (!strcmp(cmd, "PAUSE"))
  2570. rtsp_cmd_interrupt(c, url, header, 1);
  2571. else if (!strcmp(cmd, "TEARDOWN"))
  2572. rtsp_cmd_interrupt(c, url, header, 0);
  2573. else
  2574. rtsp_reply_error(c, RTSP_STATUS_METHOD);
  2575. the_end:
  2576. len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
  2577. c->pb = NULL; /* safety */
  2578. if (len < 0)
  2579. /* XXX: cannot do more */
  2580. return -1;
  2581. c->buffer_ptr = c->pb_buffer;
  2582. c->buffer_end = c->pb_buffer + len;
  2583. c->state = RTSPSTATE_SEND_REPLY;
  2584. return 0;
  2585. }
  2586. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  2587. struct in_addr my_ip)
  2588. {
  2589. AVFormatContext *avc;
  2590. AVStream *avs = NULL;
  2591. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  2592. AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
  2593. int i;
  2594. *pbuffer = NULL;
  2595. avc = avformat_alloc_context();
  2596. if (!avc || !rtp_format)
  2597. return -1;
  2598. avc->oformat = rtp_format;
  2599. av_dict_set(&avc->metadata, "title",
  2600. entry ? entry->value : "No Title", 0);
  2601. avc->nb_streams = stream->nb_streams;
  2602. if (stream->is_multicast) {
  2603. snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
  2604. inet_ntoa(stream->multicast_ip),
  2605. stream->multicast_port, stream->multicast_ttl);
  2606. } else
  2607. snprintf(avc->filename, 1024, "rtp://0.0.0.0");
  2608. avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
  2609. if (!avc->streams)
  2610. goto sdp_done;
  2611. avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
  2612. if (!avs)
  2613. goto sdp_done;
  2614. for(i = 0; i < stream->nb_streams; i++) {
  2615. avc->streams[i] = &avs[i];
  2616. avc->streams[i]->codec = stream->streams[i]->codec;
  2617. avcodec_parameters_from_context(stream->streams[i]->codecpar, stream->streams[i]->codec);
  2618. avc->streams[i]->codecpar = stream->streams[i]->codecpar;
  2619. }
  2620. *pbuffer = av_mallocz(2048);
  2621. if (!*pbuffer)
  2622. goto sdp_done;
  2623. av_sdp_create(&avc, 1, *pbuffer, 2048);
  2624. sdp_done:
  2625. av_freep(&avc->streams);
  2626. av_dict_free(&avc->metadata);
  2627. av_free(avc);
  2628. av_free(avs);
  2629. return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
  2630. }
  2631. static void rtsp_cmd_options(HTTPContext *c, const char *url)
  2632. {
  2633. /* rtsp_reply_header(c, RTSP_STATUS_OK); */
  2634. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
  2635. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2636. avio_printf(c->pb, "Public: %s\r\n",
  2637. "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
  2638. avio_printf(c->pb, "\r\n");
  2639. }
  2640. static void rtsp_cmd_describe(HTTPContext *c, const char *url)
  2641. {
  2642. FFServerStream *stream;
  2643. char path1[1024];
  2644. const char *path;
  2645. uint8_t *content;
  2646. int content_length;
  2647. socklen_t len;
  2648. struct sockaddr_in my_addr;
  2649. /* find which URL is asked */
  2650. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2651. path = path1;
  2652. if (*path == '/')
  2653. path++;
  2654. for(stream = config.first_stream; stream; stream = stream->next) {
  2655. if (!stream->is_feed &&
  2656. stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
  2657. !strcmp(path, stream->filename)) {
  2658. goto found;
  2659. }
  2660. }
  2661. /* no stream found */
  2662. rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
  2663. return;
  2664. found:
  2665. /* prepare the media description in SDP format */
  2666. /* get the host IP */
  2667. len = sizeof(my_addr);
  2668. getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
  2669. content_length = prepare_sdp_description(stream, &content,
  2670. my_addr.sin_addr);
  2671. if (content_length < 0) {
  2672. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2673. return;
  2674. }
  2675. rtsp_reply_header(c, RTSP_STATUS_OK);
  2676. avio_printf(c->pb, "Content-Base: %s/\r\n", url);
  2677. avio_printf(c->pb, "Content-Type: application/sdp\r\n");
  2678. avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
  2679. avio_printf(c->pb, "\r\n");
  2680. avio_write(c->pb, content, content_length);
  2681. av_free(content);
  2682. }
  2683. static HTTPContext *find_rtp_session(const char *session_id)
  2684. {
  2685. HTTPContext *c;
  2686. if (session_id[0] == '\0')
  2687. return NULL;
  2688. for(c = first_http_ctx; c; c = c->next) {
  2689. if (!strcmp(c->session_id, session_id))
  2690. return c;
  2691. }
  2692. return NULL;
  2693. }
  2694. static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
  2695. {
  2696. RTSPTransportField *th;
  2697. int i;
  2698. for(i=0;i<h->nb_transports;i++) {
  2699. th = &h->transports[i];
  2700. if (th->lower_transport == lower_transport)
  2701. return th;
  2702. }
  2703. return NULL;
  2704. }
  2705. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  2706. RTSPMessageHeader *h)
  2707. {
  2708. FFServerStream *stream;
  2709. int stream_index, rtp_port, rtcp_port;
  2710. char buf[1024];
  2711. char path1[1024];
  2712. const char *path;
  2713. HTTPContext *rtp_c;
  2714. RTSPTransportField *th;
  2715. struct sockaddr_in dest_addr;
  2716. RTSPActionServerSetup setup;
  2717. /* find which URL is asked */
  2718. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2719. path = path1;
  2720. if (*path == '/')
  2721. path++;
  2722. /* now check each stream */
  2723. for(stream = config.first_stream; stream; stream = stream->next) {
  2724. if (stream->is_feed || !stream->fmt ||
  2725. strcmp(stream->fmt->name, "rtp")) {
  2726. continue;
  2727. }
  2728. /* accept aggregate filenames only if single stream */
  2729. if (!strcmp(path, stream->filename)) {
  2730. if (stream->nb_streams != 1) {
  2731. rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
  2732. return;
  2733. }
  2734. stream_index = 0;
  2735. goto found;
  2736. }
  2737. for(stream_index = 0; stream_index < stream->nb_streams;
  2738. stream_index++) {
  2739. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2740. stream->filename, stream_index);
  2741. if (!strcmp(path, buf))
  2742. goto found;
  2743. }
  2744. }
  2745. /* no stream found */
  2746. rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
  2747. return;
  2748. found:
  2749. /* generate session id if needed */
  2750. if (h->session_id[0] == '\0') {
  2751. unsigned random0 = av_lfg_get(&random_state);
  2752. unsigned random1 = av_lfg_get(&random_state);
  2753. snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
  2754. random0, random1);
  2755. }
  2756. /* find RTP session, and create it if none found */
  2757. rtp_c = find_rtp_session(h->session_id);
  2758. if (!rtp_c) {
  2759. /* always prefer UDP */
  2760. th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
  2761. if (!th) {
  2762. th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
  2763. if (!th) {
  2764. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2765. return;
  2766. }
  2767. }
  2768. rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
  2769. th->lower_transport);
  2770. if (!rtp_c) {
  2771. rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
  2772. return;
  2773. }
  2774. /* open input stream */
  2775. if (open_input_stream(rtp_c, "") < 0) {
  2776. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2777. return;
  2778. }
  2779. }
  2780. /* test if stream is OK (test needed because several SETUP needs
  2781. * to be done for a given file) */
  2782. if (rtp_c->stream != stream) {
  2783. rtsp_reply_error(c, RTSP_STATUS_SERVICE);
  2784. return;
  2785. }
  2786. /* test if stream is already set up */
  2787. if (rtp_c->rtp_ctx[stream_index]) {
  2788. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2789. return;
  2790. }
  2791. /* check transport */
  2792. th = find_transport(h, rtp_c->rtp_protocol);
  2793. if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  2794. th->client_port_min <= 0)) {
  2795. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2796. return;
  2797. }
  2798. /* setup default options */
  2799. setup.transport_option[0] = '\0';
  2800. dest_addr = rtp_c->from_addr;
  2801. dest_addr.sin_port = htons(th->client_port_min);
  2802. /* setup stream */
  2803. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
  2804. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2805. return;
  2806. }
  2807. /* now everything is OK, so we can send the connection parameters */
  2808. rtsp_reply_header(c, RTSP_STATUS_OK);
  2809. /* session ID */
  2810. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2811. switch(rtp_c->rtp_protocol) {
  2812. case RTSP_LOWER_TRANSPORT_UDP:
  2813. rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
  2814. rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
  2815. avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
  2816. "client_port=%d-%d;server_port=%d-%d",
  2817. th->client_port_min, th->client_port_max,
  2818. rtp_port, rtcp_port);
  2819. break;
  2820. case RTSP_LOWER_TRANSPORT_TCP:
  2821. avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
  2822. stream_index * 2, stream_index * 2 + 1);
  2823. break;
  2824. default:
  2825. break;
  2826. }
  2827. if (setup.transport_option[0] != '\0')
  2828. avio_printf(c->pb, ";%s", setup.transport_option);
  2829. avio_printf(c->pb, "\r\n");
  2830. avio_printf(c->pb, "\r\n");
  2831. }
  2832. /**
  2833. * find an RTP connection by using the session ID. Check consistency
  2834. * with filename
  2835. */
  2836. static HTTPContext *find_rtp_session_with_url(const char *url,
  2837. const char *session_id)
  2838. {
  2839. HTTPContext *rtp_c;
  2840. char path1[1024];
  2841. const char *path;
  2842. char buf[1024];
  2843. int s, len;
  2844. rtp_c = find_rtp_session(session_id);
  2845. if (!rtp_c)
  2846. return NULL;
  2847. /* find which URL is asked */
  2848. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2849. path = path1;
  2850. if (*path == '/')
  2851. path++;
  2852. if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
  2853. for(s=0; s<rtp_c->stream->nb_streams; ++s) {
  2854. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2855. rtp_c->stream->filename, s);
  2856. if(!strncmp(path, buf, sizeof(buf)))
  2857. /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
  2858. * if nb_streams>1? */
  2859. return rtp_c;
  2860. }
  2861. len = strlen(path);
  2862. if (len > 0 && path[len - 1] == '/' &&
  2863. !strncmp(path, rtp_c->stream->filename, len - 1))
  2864. return rtp_c;
  2865. return NULL;
  2866. }
  2867. static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
  2868. {
  2869. HTTPContext *rtp_c;
  2870. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2871. if (!rtp_c) {
  2872. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2873. return;
  2874. }
  2875. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2876. rtp_c->state != HTTPSTATE_WAIT_FEED &&
  2877. rtp_c->state != HTTPSTATE_READY) {
  2878. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2879. return;
  2880. }
  2881. rtp_c->state = HTTPSTATE_SEND_DATA;
  2882. /* now everything is OK, so we can send the connection parameters */
  2883. rtsp_reply_header(c, RTSP_STATUS_OK);
  2884. /* session ID */
  2885. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2886. avio_printf(c->pb, "\r\n");
  2887. }
  2888. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  2889. RTSPMessageHeader *h, int pause_only)
  2890. {
  2891. HTTPContext *rtp_c;
  2892. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2893. if (!rtp_c) {
  2894. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2895. return;
  2896. }
  2897. if (pause_only) {
  2898. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2899. rtp_c->state != HTTPSTATE_WAIT_FEED) {
  2900. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2901. return;
  2902. }
  2903. rtp_c->state = HTTPSTATE_READY;
  2904. rtp_c->first_pts = AV_NOPTS_VALUE;
  2905. }
  2906. /* now everything is OK, so we can send the connection parameters */
  2907. rtsp_reply_header(c, RTSP_STATUS_OK);
  2908. /* session ID */
  2909. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2910. avio_printf(c->pb, "\r\n");
  2911. if (!pause_only)
  2912. close_connection(rtp_c);
  2913. }
  2914. /********************************************************************/
  2915. /* RTP handling */
  2916. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  2917. FFServerStream *stream,
  2918. const char *session_id,
  2919. enum RTSPLowerTransport rtp_protocol)
  2920. {
  2921. HTTPContext *c = NULL;
  2922. const char *proto_str;
  2923. /* XXX: should output a warning page when coming
  2924. * close to the connection limit */
  2925. if (nb_connections >= config.nb_max_connections)
  2926. goto fail;
  2927. /* add a new connection */
  2928. c = av_mallocz(sizeof(HTTPContext));
  2929. if (!c)
  2930. goto fail;
  2931. c->fd = -1;
  2932. c->poll_entry = NULL;
  2933. c->from_addr = *from_addr;
  2934. c->buffer_size = IOBUFFER_INIT_SIZE;
  2935. c->buffer = av_malloc(c->buffer_size);
  2936. if (!c->buffer)
  2937. goto fail;
  2938. nb_connections++;
  2939. c->stream = stream;
  2940. av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
  2941. c->state = HTTPSTATE_READY;
  2942. c->is_packetized = 1;
  2943. c->rtp_protocol = rtp_protocol;
  2944. /* protocol is shown in statistics */
  2945. switch(c->rtp_protocol) {
  2946. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  2947. proto_str = "MCAST";
  2948. break;
  2949. case RTSP_LOWER_TRANSPORT_UDP:
  2950. proto_str = "UDP";
  2951. break;
  2952. case RTSP_LOWER_TRANSPORT_TCP:
  2953. proto_str = "TCP";
  2954. break;
  2955. default:
  2956. proto_str = "???";
  2957. break;
  2958. }
  2959. av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
  2960. av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
  2961. current_bandwidth += stream->bandwidth;
  2962. c->next = first_http_ctx;
  2963. first_http_ctx = c;
  2964. return c;
  2965. fail:
  2966. if (c) {
  2967. av_freep(&c->buffer);
  2968. av_free(c);
  2969. }
  2970. return NULL;
  2971. }
  2972. /**
  2973. * add a new RTP stream in an RTP connection (used in RTSP SETUP
  2974. * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
  2975. * used.
  2976. */
  2977. static int rtp_new_av_stream(HTTPContext *c,
  2978. int stream_index, struct sockaddr_in *dest_addr,
  2979. HTTPContext *rtsp_c)
  2980. {
  2981. AVFormatContext *ctx;
  2982. AVStream *st;
  2983. char *ipaddr;
  2984. URLContext *h = NULL;
  2985. uint8_t *dummy_buf;
  2986. int max_packet_size;
  2987. void *st_internal;
  2988. /* now we can open the relevant output stream */
  2989. ctx = avformat_alloc_context();
  2990. if (!ctx)
  2991. return -1;
  2992. ctx->oformat = av_guess_format("rtp", NULL, NULL);
  2993. st = avformat_new_stream(ctx, NULL);
  2994. if (!st)
  2995. goto fail;
  2996. av_freep(&st->codec);
  2997. av_freep(&st->info);
  2998. st_internal = st->internal;
  2999. if (!c->stream->feed ||
  3000. c->stream->feed == c->stream)
  3001. memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
  3002. else
  3003. memcpy(st,
  3004. c->stream->feed->streams[c->stream->feed_streams[stream_index]],
  3005. sizeof(AVStream));
  3006. st->priv_data = NULL;
  3007. st->internal = st_internal;
  3008. /* build destination RTP address */
  3009. ipaddr = inet_ntoa(dest_addr->sin_addr);
  3010. switch(c->rtp_protocol) {
  3011. case RTSP_LOWER_TRANSPORT_UDP:
  3012. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  3013. /* RTP/UDP case */
  3014. /* XXX: also pass as parameter to function ? */
  3015. if (c->stream->is_multicast) {
  3016. int ttl;
  3017. ttl = c->stream->multicast_ttl;
  3018. if (!ttl)
  3019. ttl = 16;
  3020. snprintf(ctx->filename, sizeof(ctx->filename),
  3021. "rtp://%s:%d?multicast=1&ttl=%d",
  3022. ipaddr, ntohs(dest_addr->sin_port), ttl);
  3023. } else {
  3024. snprintf(ctx->filename, sizeof(ctx->filename),
  3025. "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
  3026. }
  3027. if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
  3028. goto fail;
  3029. c->rtp_handles[stream_index] = h;
  3030. max_packet_size = h->max_packet_size;
  3031. break;
  3032. case RTSP_LOWER_TRANSPORT_TCP:
  3033. /* RTP/TCP case */
  3034. c->rtsp_c = rtsp_c;
  3035. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  3036. break;
  3037. default:
  3038. goto fail;
  3039. }
  3040. http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
  3041. ipaddr, ntohs(dest_addr->sin_port),
  3042. c->stream->filename, stream_index, c->protocol);
  3043. /* normally, no packets should be output here, but the packet size may
  3044. * be checked */
  3045. if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
  3046. /* XXX: close stream */
  3047. goto fail;
  3048. if (avformat_write_header(ctx, NULL) < 0) {
  3049. fail:
  3050. if (h)
  3051. ffurl_close(h);
  3052. av_free(st);
  3053. av_free(ctx);
  3054. return -1;
  3055. }
  3056. avio_close_dyn_buf(ctx->pb, &dummy_buf);
  3057. ctx->pb = NULL;
  3058. av_free(dummy_buf);
  3059. c->rtp_ctx[stream_index] = ctx;
  3060. return 0;
  3061. }
  3062. /********************************************************************/
  3063. /* ffserver initialization */
  3064. /* FIXME: This code should use avformat_new_stream() */
  3065. static AVStream *add_av_stream1(FFServerStream *stream,
  3066. AVCodecContext *codec, int copy)
  3067. {
  3068. AVStream *fst;
  3069. if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
  3070. return NULL;
  3071. fst = av_mallocz(sizeof(AVStream));
  3072. if (!fst)
  3073. return NULL;
  3074. if (copy) {
  3075. fst->codec = avcodec_alloc_context3(codec->codec);
  3076. if (!fst->codec) {
  3077. av_free(fst);
  3078. return NULL;
  3079. }
  3080. avcodec_copy_context(fst->codec, codec);
  3081. } else
  3082. /* live streams must use the actual feed's codec since it may be
  3083. * updated later to carry extradata needed by them.
  3084. */
  3085. fst->codec = codec;
  3086. fst->priv_data = av_mallocz(sizeof(FeedData));
  3087. fst->internal = av_mallocz(sizeof(*fst->internal));
  3088. fst->internal->avctx = avcodec_alloc_context3(NULL);
  3089. fst->codecpar = avcodec_parameters_alloc();
  3090. fst->index = stream->nb_streams;
  3091. avpriv_set_pts_info(fst, 33, 1, 90000);
  3092. fst->sample_aspect_ratio = codec->sample_aspect_ratio;
  3093. stream->streams[stream->nb_streams++] = fst;
  3094. return fst;
  3095. }
  3096. /* return the stream number in the feed */
  3097. static int add_av_stream(FFServerStream *feed, AVStream *st)
  3098. {
  3099. AVStream *fst;
  3100. AVCodecContext *av, *av1;
  3101. int i;
  3102. av = st->codec;
  3103. for(i=0;i<feed->nb_streams;i++) {
  3104. av1 = feed->streams[i]->codec;
  3105. if (av1->codec_id == av->codec_id &&
  3106. av1->codec_type == av->codec_type &&
  3107. av1->bit_rate == av->bit_rate) {
  3108. switch(av->codec_type) {
  3109. case AVMEDIA_TYPE_AUDIO:
  3110. if (av1->channels == av->channels &&
  3111. av1->sample_rate == av->sample_rate)
  3112. return i;
  3113. break;
  3114. case AVMEDIA_TYPE_VIDEO:
  3115. if (av1->width == av->width &&
  3116. av1->height == av->height &&
  3117. av1->time_base.den == av->time_base.den &&
  3118. av1->time_base.num == av->time_base.num &&
  3119. av1->gop_size == av->gop_size)
  3120. return i;
  3121. break;
  3122. default:
  3123. abort();
  3124. }
  3125. }
  3126. }
  3127. fst = add_av_stream1(feed, av, 0);
  3128. if (!fst)
  3129. return -1;
  3130. if (av_stream_get_recommended_encoder_configuration(st))
  3131. av_stream_set_recommended_encoder_configuration(fst,
  3132. av_strdup(av_stream_get_recommended_encoder_configuration(st)));
  3133. return feed->nb_streams - 1;
  3134. }
  3135. static void remove_stream(FFServerStream *stream)
  3136. {
  3137. FFServerStream **ps;
  3138. ps = &config.first_stream;
  3139. while (*ps) {
  3140. if (*ps == stream)
  3141. *ps = (*ps)->next;
  3142. else
  3143. ps = &(*ps)->next;
  3144. }
  3145. }
  3146. /* specific MPEG4 handling : we extract the raw parameters */
  3147. static void extract_mpeg4_header(AVFormatContext *infile)
  3148. {
  3149. int mpeg4_count, i, size;
  3150. AVPacket pkt;
  3151. AVStream *st;
  3152. const uint8_t *p;
  3153. infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
  3154. mpeg4_count = 0;
  3155. for(i=0;i<infile->nb_streams;i++) {
  3156. st = infile->streams[i];
  3157. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3158. st->codec->extradata_size == 0) {
  3159. mpeg4_count++;
  3160. }
  3161. }
  3162. if (!mpeg4_count)
  3163. return;
  3164. printf("MPEG4 without extra data: trying to find header in %s\n",
  3165. infile->filename);
  3166. while (mpeg4_count > 0) {
  3167. if (av_read_frame(infile, &pkt) < 0)
  3168. break;
  3169. st = infile->streams[pkt.stream_index];
  3170. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3171. st->codec->extradata_size == 0) {
  3172. av_freep(&st->codec->extradata);
  3173. /* fill extradata with the header */
  3174. /* XXX: we make hard suppositions here ! */
  3175. p = pkt.data;
  3176. while (p < pkt.data + pkt.size - 4) {
  3177. /* stop when vop header is found */
  3178. if (p[0] == 0x00 && p[1] == 0x00 &&
  3179. p[2] == 0x01 && p[3] == 0xb6) {
  3180. size = p - pkt.data;
  3181. st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  3182. st->codec->extradata_size = size;
  3183. memcpy(st->codec->extradata, pkt.data, size);
  3184. break;
  3185. }
  3186. p++;
  3187. }
  3188. mpeg4_count--;
  3189. }
  3190. av_packet_unref(&pkt);
  3191. }
  3192. }
  3193. /* compute the needed AVStream for each file */
  3194. static void build_file_streams(void)
  3195. {
  3196. FFServerStream *stream;
  3197. AVFormatContext *infile;
  3198. int i, ret;
  3199. /* gather all streams */
  3200. for(stream = config.first_stream; stream; stream = stream->next) {
  3201. infile = NULL;
  3202. if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
  3203. continue;
  3204. /* the stream comes from a file */
  3205. /* try to open the file */
  3206. /* open stream */
  3207. /* specific case: if transport stream output to RTP,
  3208. * we use a raw transport stream reader */
  3209. if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
  3210. av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
  3211. if (!stream->feed_filename[0]) {
  3212. http_log("Unspecified feed file for stream '%s'\n",
  3213. stream->filename);
  3214. goto fail;
  3215. }
  3216. http_log("Opening feed file '%s' for stream '%s'\n",
  3217. stream->feed_filename, stream->filename);
  3218. ret = avformat_open_input(&infile, stream->feed_filename,
  3219. stream->ifmt, &stream->in_opts);
  3220. if (ret < 0) {
  3221. http_log("Could not open '%s': %s\n", stream->feed_filename,
  3222. av_err2str(ret));
  3223. /* remove stream (no need to spend more time on it) */
  3224. fail:
  3225. remove_stream(stream);
  3226. } else {
  3227. /* find all the AVStreams inside and reference them in
  3228. * 'stream' */
  3229. if (avformat_find_stream_info(infile, NULL) < 0) {
  3230. http_log("Could not find codec parameters from '%s'\n",
  3231. stream->feed_filename);
  3232. avformat_close_input(&infile);
  3233. goto fail;
  3234. }
  3235. extract_mpeg4_header(infile);
  3236. for(i=0;i<infile->nb_streams;i++)
  3237. add_av_stream1(stream, infile->streams[i]->codec, 1);
  3238. avformat_close_input(&infile);
  3239. }
  3240. }
  3241. }
  3242. static inline
  3243. int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs, int stream)
  3244. {
  3245. int matches = 1;
  3246. #define CHECK_CODEC(x) (ccf->x != ccs->x)
  3247. if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
  3248. http_log("Codecs do not match for stream %d\n", stream);
  3249. matches = 0;
  3250. } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
  3251. http_log("Codec bitrates do not match for stream %d\n", stream);
  3252. matches = 0;
  3253. } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
  3254. if (CHECK_CODEC(time_base.den) ||
  3255. CHECK_CODEC(time_base.num) ||
  3256. CHECK_CODEC(width) ||
  3257. CHECK_CODEC(height)) {
  3258. http_log("Codec width, height or framerate do not match for stream %d\n", stream);
  3259. matches = 0;
  3260. }
  3261. } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
  3262. if (CHECK_CODEC(sample_rate) ||
  3263. CHECK_CODEC(channels) ||
  3264. CHECK_CODEC(frame_size)) {
  3265. http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
  3266. matches = 0;
  3267. }
  3268. } else {
  3269. http_log("Unknown codec type for stream %d\n", stream);
  3270. matches = 0;
  3271. }
  3272. return matches;
  3273. }
  3274. /* compute the needed AVStream for each feed */
  3275. static int build_feed_streams(void)
  3276. {
  3277. FFServerStream *stream, *feed;
  3278. int i, fd;
  3279. /* gather all streams */
  3280. for(stream = config.first_stream; stream; stream = stream->next) {
  3281. feed = stream->feed;
  3282. if (!feed)
  3283. continue;
  3284. if (stream->is_feed) {
  3285. for(i=0;i<stream->nb_streams;i++)
  3286. stream->feed_streams[i] = i;
  3287. continue;
  3288. }
  3289. /* we handle a stream coming from a feed */
  3290. for(i=0;i<stream->nb_streams;i++)
  3291. stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
  3292. }
  3293. /* create feed files if needed */
  3294. for(feed = config.first_feed; feed; feed = feed->next_feed) {
  3295. if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
  3296. AVFormatContext *s = NULL;
  3297. int matches = 0;
  3298. /* See if it matches */
  3299. if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
  3300. http_log("Deleting feed file '%s' as it appears "
  3301. "to be corrupt\n",
  3302. feed->feed_filename);
  3303. goto drop;
  3304. }
  3305. /* set buffer size */
  3306. if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
  3307. http_log("Failed to set buffer size\n");
  3308. avformat_close_input(&s);
  3309. goto bail;
  3310. }
  3311. /* Now see if it matches */
  3312. if (s->nb_streams != feed->nb_streams) {
  3313. http_log("Deleting feed file '%s' as stream counts "
  3314. "differ (%d != %d)\n",
  3315. feed->feed_filename, s->nb_streams, feed->nb_streams);
  3316. goto drop;
  3317. }
  3318. matches = 1;
  3319. for(i=0;i<s->nb_streams;i++) {
  3320. AVStream *sf, *ss;
  3321. sf = feed->streams[i];
  3322. ss = s->streams[i];
  3323. if (sf->index != ss->index || sf->id != ss->id) {
  3324. http_log("Index & Id do not match for stream %d (%s)\n",
  3325. i, feed->feed_filename);
  3326. matches = 0;
  3327. break;
  3328. }
  3329. matches = check_codec_match (sf->codec, ss->codec, i);
  3330. if (!matches)
  3331. break;
  3332. }
  3333. drop:
  3334. if (s)
  3335. avformat_close_input(&s);
  3336. if (!matches) {
  3337. if (feed->readonly) {
  3338. http_log("Unable to delete read-only feed file '%s'\n",
  3339. feed->feed_filename);
  3340. goto bail;
  3341. }
  3342. unlink(feed->feed_filename);
  3343. }
  3344. }
  3345. if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
  3346. AVFormatContext *s = avformat_alloc_context();
  3347. if (!s) {
  3348. http_log("Failed to allocate context\n");
  3349. goto bail;
  3350. }
  3351. if (feed->readonly) {
  3352. http_log("Unable to create feed file '%s' as it is "
  3353. "marked readonly\n",
  3354. feed->feed_filename);
  3355. avformat_free_context(s);
  3356. goto bail;
  3357. }
  3358. /* only write the header of the ffm file */
  3359. if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
  3360. http_log("Could not open output feed file '%s'\n",
  3361. feed->feed_filename);
  3362. avformat_free_context(s);
  3363. goto bail;
  3364. }
  3365. s->oformat = feed->fmt;
  3366. s->nb_streams = feed->nb_streams;
  3367. s->streams = feed->streams;
  3368. if (avformat_write_header(s, NULL) < 0) {
  3369. http_log("Container doesn't support the required parameters\n");
  3370. avio_closep(&s->pb);
  3371. s->streams = NULL;
  3372. s->nb_streams = 0;
  3373. avformat_free_context(s);
  3374. goto bail;
  3375. }
  3376. /* XXX: need better API */
  3377. av_freep(&s->priv_data);
  3378. avio_closep(&s->pb);
  3379. s->streams = NULL;
  3380. s->nb_streams = 0;
  3381. avformat_free_context(s);
  3382. }
  3383. /* get feed size and write index */
  3384. fd = open(feed->feed_filename, O_RDONLY);
  3385. if (fd < 0) {
  3386. http_log("Could not open output feed file '%s'\n",
  3387. feed->feed_filename);
  3388. goto bail;
  3389. }
  3390. feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
  3391. FFM_PACKET_SIZE);
  3392. feed->feed_size = lseek(fd, 0, SEEK_END);
  3393. /* ensure that we do not wrap before the end of file */
  3394. if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
  3395. feed->feed_max_size = feed->feed_size;
  3396. close(fd);
  3397. }
  3398. return 0;
  3399. bail:
  3400. return -1;
  3401. }
  3402. /* compute the bandwidth used by each stream */
  3403. static void compute_bandwidth(void)
  3404. {
  3405. unsigned bandwidth;
  3406. int i;
  3407. FFServerStream *stream;
  3408. for(stream = config.first_stream; stream; stream = stream->next) {
  3409. bandwidth = 0;
  3410. for(i=0;i<stream->nb_streams;i++) {
  3411. AVStream *st = stream->streams[i];
  3412. switch(st->codec->codec_type) {
  3413. case AVMEDIA_TYPE_AUDIO:
  3414. case AVMEDIA_TYPE_VIDEO:
  3415. bandwidth += st->codec->bit_rate;
  3416. break;
  3417. default:
  3418. break;
  3419. }
  3420. }
  3421. stream->bandwidth = (bandwidth + 999) / 1000;
  3422. }
  3423. }
  3424. static void handle_child_exit(int sig)
  3425. {
  3426. pid_t pid;
  3427. int status;
  3428. time_t uptime;
  3429. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  3430. FFServerStream *feed;
  3431. for (feed = config.first_feed; feed; feed = feed->next) {
  3432. if (feed->pid != pid)
  3433. continue;
  3434. uptime = time(0) - feed->pid_start;
  3435. feed->pid = 0;
  3436. fprintf(stderr,
  3437. "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
  3438. "seconds\n",
  3439. feed->filename, (int64_t) pid, status, (int64_t)uptime);
  3440. if (uptime < 30)
  3441. /* Turn off any more restarts */
  3442. ffserver_free_child_args(&feed->child_argv);
  3443. }
  3444. }
  3445. need_to_start_children = 1;
  3446. }
  3447. static void opt_debug(void)
  3448. {
  3449. config.debug = 1;
  3450. snprintf(config.logfilename, sizeof(config.logfilename), "-");
  3451. }
  3452. void show_help_default(const char *opt, const char *arg)
  3453. {
  3454. printf("usage: ffserver [options]\n"
  3455. "Hyper fast multi format Audio/Video streaming server\n");
  3456. printf("\n");
  3457. show_help_options(options, "Main options:", 0, 0, 0);
  3458. }
  3459. static const OptionDef options[] = {
  3460. #include "cmdutils_common_opts.h"
  3461. { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
  3462. { "d", 0, {(void*)opt_debug}, "enable debug mode" },
  3463. { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
  3464. { NULL },
  3465. };
  3466. int main(int argc, char **argv)
  3467. {
  3468. struct sigaction sigact = { { 0 } };
  3469. int cfg_parsed;
  3470. int ret = EXIT_FAILURE;
  3471. init_dynload();
  3472. config.filename = av_strdup("/etc/ffserver.conf");
  3473. parse_loglevel(argc, argv, options);
  3474. av_register_all();
  3475. avformat_network_init();
  3476. show_banner(argc, argv, options);
  3477. my_program_name = argv[0];
  3478. parse_options(NULL, argc, argv, options, NULL);
  3479. unsetenv("http_proxy"); /* Kill the http_proxy */
  3480. av_lfg_init(&random_state, av_get_random_seed());
  3481. sigact.sa_handler = handle_child_exit;
  3482. sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  3483. sigaction(SIGCHLD, &sigact, 0);
  3484. if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
  3485. fprintf(stderr, "Error reading configuration file '%s': %s\n",
  3486. config.filename, av_err2str(cfg_parsed));
  3487. goto bail;
  3488. }
  3489. /* open log file if needed */
  3490. if (config.logfilename[0] != '\0') {
  3491. if (!strcmp(config.logfilename, "-"))
  3492. logfile = stdout;
  3493. else
  3494. logfile = fopen(config.logfilename, "a");
  3495. av_log_set_callback(http_av_log);
  3496. }
  3497. build_file_streams();
  3498. if (build_feed_streams() < 0) {
  3499. http_log("Could not setup feed streams\n");
  3500. goto bail;
  3501. }
  3502. compute_bandwidth();
  3503. /* signal init */
  3504. signal(SIGPIPE, SIG_IGN);
  3505. if (http_server() < 0) {
  3506. http_log("Could not start server\n");
  3507. goto bail;
  3508. }
  3509. ret=EXIT_SUCCESS;
  3510. bail:
  3511. av_freep (&config.filename);
  3512. avformat_network_deinit();
  3513. return ret;
  3514. }