ffserver.c 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041
  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. if (c->stream->feed_opened) {
  2291. http_log("Stream feed '%s' was not opened\n",
  2292. c->stream->feed_filename);
  2293. return AVERROR(EINVAL);
  2294. }
  2295. /* Don't permit writing to this one */
  2296. if (c->stream->readonly) {
  2297. http_log("Cannot write to read-only file '%s'\n",
  2298. c->stream->feed_filename);
  2299. return AVERROR(EINVAL);
  2300. }
  2301. /* open feed */
  2302. fd = open(c->stream->feed_filename, O_RDWR);
  2303. if (fd < 0) {
  2304. ret = AVERROR(errno);
  2305. http_log("Could not open feed file '%s': %s\n",
  2306. c->stream->feed_filename, strerror(errno));
  2307. return ret;
  2308. }
  2309. c->feed_fd = fd;
  2310. if (c->stream->truncate) {
  2311. /* truncate feed file */
  2312. ffm_write_write_index(c->feed_fd, FFM_PACKET_SIZE);
  2313. http_log("Truncating feed file '%s'\n", c->stream->feed_filename);
  2314. if (ftruncate(c->feed_fd, FFM_PACKET_SIZE) < 0) {
  2315. ret = AVERROR(errno);
  2316. http_log("Error truncating feed file '%s': %s\n",
  2317. c->stream->feed_filename, strerror(errno));
  2318. return ret;
  2319. }
  2320. } else {
  2321. ret = ffm_read_write_index(fd);
  2322. if (ret < 0) {
  2323. http_log("Error reading write index from feed file '%s': %s\n",
  2324. c->stream->feed_filename, strerror(errno));
  2325. return ret;
  2326. }
  2327. c->stream->feed_write_index = ret;
  2328. }
  2329. c->stream->feed_write_index = FFMAX(ffm_read_write_index(fd),
  2330. FFM_PACKET_SIZE);
  2331. c->stream->feed_size = lseek(fd, 0, SEEK_END);
  2332. lseek(fd, 0, SEEK_SET);
  2333. /* init buffer input */
  2334. c->buffer_ptr = c->buffer;
  2335. c->buffer_end = c->buffer + FFM_PACKET_SIZE;
  2336. c->stream->feed_opened = 1;
  2337. c->chunked_encoding = !!av_stristr(c->buffer, "Transfer-Encoding: chunked");
  2338. return 0;
  2339. }
  2340. static int http_receive_data(HTTPContext *c)
  2341. {
  2342. HTTPContext *c1;
  2343. int len, loop_run = 0;
  2344. while (c->chunked_encoding && !c->chunk_size &&
  2345. c->buffer_end > c->buffer_ptr) {
  2346. /* read chunk header, if present */
  2347. len = recv(c->fd, c->buffer_ptr, 1, 0);
  2348. if (len < 0) {
  2349. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2350. ff_neterrno() != AVERROR(EINTR))
  2351. /* error : close connection */
  2352. goto fail;
  2353. return 0;
  2354. } else if (len == 0) {
  2355. /* end of connection : close it */
  2356. goto fail;
  2357. } else if (c->buffer_ptr - c->buffer >= 2 &&
  2358. !memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
  2359. c->chunk_size = strtol(c->buffer, 0, 16);
  2360. if (c->chunk_size <= 0) { // end of stream or invalid chunk size
  2361. c->chunk_size = 0;
  2362. goto fail;
  2363. }
  2364. c->buffer_ptr = c->buffer;
  2365. break;
  2366. } else if (++loop_run > 10)
  2367. /* no chunk header, abort */
  2368. goto fail;
  2369. else
  2370. c->buffer_ptr++;
  2371. }
  2372. if (c->buffer_end > c->buffer_ptr) {
  2373. len = recv(c->fd, c->buffer_ptr,
  2374. FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
  2375. if (len < 0) {
  2376. if (ff_neterrno() != AVERROR(EAGAIN) &&
  2377. ff_neterrno() != AVERROR(EINTR))
  2378. /* error : close connection */
  2379. goto fail;
  2380. } else if (len == 0)
  2381. /* end of connection : close it */
  2382. goto fail;
  2383. else {
  2384. av_assert0(len <= c->chunk_size);
  2385. c->chunk_size -= len;
  2386. c->buffer_ptr += len;
  2387. c->data_count += len;
  2388. update_datarate(&c->datarate, c->data_count);
  2389. }
  2390. }
  2391. if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
  2392. if (c->buffer[0] != 'f' ||
  2393. c->buffer[1] != 'm') {
  2394. http_log("Feed stream has become desynchronized -- disconnecting\n");
  2395. goto fail;
  2396. }
  2397. }
  2398. if (c->buffer_ptr >= c->buffer_end) {
  2399. FFServerStream *feed = c->stream;
  2400. /* a packet has been received : write it in the store, except
  2401. * if header */
  2402. if (c->data_count > FFM_PACKET_SIZE) {
  2403. /* XXX: use llseek or url_seek
  2404. * XXX: Should probably fail? */
  2405. if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
  2406. http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
  2407. if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
  2408. http_log("Error writing to feed file: %s\n", strerror(errno));
  2409. goto fail;
  2410. }
  2411. feed->feed_write_index += FFM_PACKET_SIZE;
  2412. /* update file size */
  2413. if (feed->feed_write_index > c->stream->feed_size)
  2414. feed->feed_size = feed->feed_write_index;
  2415. /* handle wrap around if max file size reached */
  2416. if (c->stream->feed_max_size &&
  2417. feed->feed_write_index >= c->stream->feed_max_size)
  2418. feed->feed_write_index = FFM_PACKET_SIZE;
  2419. /* write index */
  2420. if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
  2421. http_log("Error writing index to feed file: %s\n",
  2422. strerror(errno));
  2423. goto fail;
  2424. }
  2425. /* wake up any waiting connections */
  2426. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2427. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2428. c1->stream->feed == c->stream->feed)
  2429. c1->state = HTTPSTATE_SEND_DATA;
  2430. }
  2431. } else {
  2432. /* We have a header in our hands that contains useful data */
  2433. AVFormatContext *s = avformat_alloc_context();
  2434. AVIOContext *pb;
  2435. AVInputFormat *fmt_in;
  2436. int i;
  2437. if (!s)
  2438. goto fail;
  2439. /* use feed output format name to find corresponding input format */
  2440. fmt_in = av_find_input_format(feed->fmt->name);
  2441. if (!fmt_in)
  2442. goto fail;
  2443. pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
  2444. 0, NULL, NULL, NULL, NULL);
  2445. if (!pb)
  2446. goto fail;
  2447. pb->seekable = 0;
  2448. s->pb = pb;
  2449. if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
  2450. av_freep(&pb);
  2451. goto fail;
  2452. }
  2453. /* Now we have the actual streams */
  2454. if (s->nb_streams != feed->nb_streams) {
  2455. avformat_close_input(&s);
  2456. av_freep(&pb);
  2457. http_log("Feed '%s' stream number does not match registered feed\n",
  2458. c->stream->feed_filename);
  2459. goto fail;
  2460. }
  2461. for (i = 0; i < s->nb_streams; i++) {
  2462. AVStream *fst = feed->streams[i];
  2463. AVStream *st = s->streams[i];
  2464. avcodec_copy_context(fst->codec, st->codec);
  2465. }
  2466. avformat_close_input(&s);
  2467. av_freep(&pb);
  2468. }
  2469. c->buffer_ptr = c->buffer;
  2470. }
  2471. return 0;
  2472. fail:
  2473. c->stream->feed_opened = 0;
  2474. close(c->feed_fd);
  2475. /* wake up any waiting connections to stop waiting for feed */
  2476. for(c1 = first_http_ctx; c1; c1 = c1->next) {
  2477. if (c1->state == HTTPSTATE_WAIT_FEED &&
  2478. c1->stream->feed == c->stream->feed)
  2479. c1->state = HTTPSTATE_SEND_DATA_TRAILER;
  2480. }
  2481. return -1;
  2482. }
  2483. /********************************************************************/
  2484. /* RTSP handling */
  2485. static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number)
  2486. {
  2487. const char *str;
  2488. time_t ti;
  2489. struct tm *tm;
  2490. char buf2[32];
  2491. str = RTSP_STATUS_CODE2STRING(error_number);
  2492. if (!str)
  2493. str = "Unknown Error";
  2494. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str);
  2495. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2496. /* output GMT time */
  2497. ti = time(NULL);
  2498. tm = gmtime(&ti);
  2499. strftime(buf2, sizeof(buf2), "%a, %d %b %Y %H:%M:%S", tm);
  2500. avio_printf(c->pb, "Date: %s GMT\r\n", buf2);
  2501. }
  2502. static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number)
  2503. {
  2504. rtsp_reply_header(c, error_number);
  2505. avio_printf(c->pb, "\r\n");
  2506. }
  2507. static int rtsp_parse_request(HTTPContext *c)
  2508. {
  2509. const char *p, *p1, *p2;
  2510. char cmd[32];
  2511. char url[1024];
  2512. char protocol[32];
  2513. char line[1024];
  2514. int len;
  2515. RTSPMessageHeader header1 = { 0 }, *header = &header1;
  2516. c->buffer_ptr[0] = '\0';
  2517. p = c->buffer;
  2518. get_word(cmd, sizeof(cmd), &p);
  2519. get_word(url, sizeof(url), &p);
  2520. get_word(protocol, sizeof(protocol), &p);
  2521. av_strlcpy(c->method, cmd, sizeof(c->method));
  2522. av_strlcpy(c->url, url, sizeof(c->url));
  2523. av_strlcpy(c->protocol, protocol, sizeof(c->protocol));
  2524. if (avio_open_dyn_buf(&c->pb) < 0) {
  2525. /* XXX: cannot do more */
  2526. c->pb = NULL; /* safety */
  2527. return -1;
  2528. }
  2529. /* check version name */
  2530. if (strcmp(protocol, "RTSP/1.0")) {
  2531. rtsp_reply_error(c, RTSP_STATUS_VERSION);
  2532. goto the_end;
  2533. }
  2534. /* parse each header line */
  2535. /* skip to next line */
  2536. while (*p != '\n' && *p != '\0')
  2537. p++;
  2538. if (*p == '\n')
  2539. p++;
  2540. while (*p != '\0') {
  2541. p1 = memchr(p, '\n', (char *)c->buffer_ptr - p);
  2542. if (!p1)
  2543. break;
  2544. p2 = p1;
  2545. if (p2 > p && p2[-1] == '\r')
  2546. p2--;
  2547. /* skip empty line */
  2548. if (p2 == p)
  2549. break;
  2550. len = p2 - p;
  2551. if (len > sizeof(line) - 1)
  2552. len = sizeof(line) - 1;
  2553. memcpy(line, p, len);
  2554. line[len] = '\0';
  2555. ff_rtsp_parse_line(NULL, header, line, NULL, NULL);
  2556. p = p1 + 1;
  2557. }
  2558. /* handle sequence number */
  2559. c->seq = header->seq;
  2560. if (!strcmp(cmd, "DESCRIBE"))
  2561. rtsp_cmd_describe(c, url);
  2562. else if (!strcmp(cmd, "OPTIONS"))
  2563. rtsp_cmd_options(c, url);
  2564. else if (!strcmp(cmd, "SETUP"))
  2565. rtsp_cmd_setup(c, url, header);
  2566. else if (!strcmp(cmd, "PLAY"))
  2567. rtsp_cmd_play(c, url, header);
  2568. else if (!strcmp(cmd, "PAUSE"))
  2569. rtsp_cmd_interrupt(c, url, header, 1);
  2570. else if (!strcmp(cmd, "TEARDOWN"))
  2571. rtsp_cmd_interrupt(c, url, header, 0);
  2572. else
  2573. rtsp_reply_error(c, RTSP_STATUS_METHOD);
  2574. the_end:
  2575. len = avio_close_dyn_buf(c->pb, &c->pb_buffer);
  2576. c->pb = NULL; /* safety */
  2577. if (len < 0)
  2578. /* XXX: cannot do more */
  2579. return -1;
  2580. c->buffer_ptr = c->pb_buffer;
  2581. c->buffer_end = c->pb_buffer + len;
  2582. c->state = RTSPSTATE_SEND_REPLY;
  2583. return 0;
  2584. }
  2585. static int prepare_sdp_description(FFServerStream *stream, uint8_t **pbuffer,
  2586. struct in_addr my_ip)
  2587. {
  2588. AVFormatContext *avc;
  2589. AVStream *avs = NULL;
  2590. AVOutputFormat *rtp_format = av_guess_format("rtp", NULL, NULL);
  2591. AVDictionaryEntry *entry = av_dict_get(stream->metadata, "title", NULL, 0);
  2592. int i;
  2593. *pbuffer = NULL;
  2594. avc = avformat_alloc_context();
  2595. if (!avc || !rtp_format)
  2596. return -1;
  2597. avc->oformat = rtp_format;
  2598. av_dict_set(&avc->metadata, "title",
  2599. entry ? entry->value : "No Title", 0);
  2600. avc->nb_streams = stream->nb_streams;
  2601. if (stream->is_multicast) {
  2602. snprintf(avc->filename, 1024, "rtp://%s:%d?multicast=1?ttl=%d",
  2603. inet_ntoa(stream->multicast_ip),
  2604. stream->multicast_port, stream->multicast_ttl);
  2605. } else
  2606. snprintf(avc->filename, 1024, "rtp://0.0.0.0");
  2607. avc->streams = av_malloc_array(avc->nb_streams, sizeof(*avc->streams));
  2608. if (!avc->streams)
  2609. goto sdp_done;
  2610. avs = av_malloc_array(avc->nb_streams, sizeof(*avs));
  2611. if (!avs)
  2612. goto sdp_done;
  2613. for(i = 0; i < stream->nb_streams; i++) {
  2614. avc->streams[i] = &avs[i];
  2615. avc->streams[i]->codec = stream->streams[i]->codec;
  2616. }
  2617. *pbuffer = av_mallocz(2048);
  2618. if (!*pbuffer)
  2619. goto sdp_done;
  2620. av_sdp_create(&avc, 1, *pbuffer, 2048);
  2621. sdp_done:
  2622. av_freep(&avc->streams);
  2623. av_dict_free(&avc->metadata);
  2624. av_free(avc);
  2625. av_free(avs);
  2626. return *pbuffer ? strlen(*pbuffer) : AVERROR(ENOMEM);
  2627. }
  2628. static void rtsp_cmd_options(HTTPContext *c, const char *url)
  2629. {
  2630. /* rtsp_reply_header(c, RTSP_STATUS_OK); */
  2631. avio_printf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK");
  2632. avio_printf(c->pb, "CSeq: %d\r\n", c->seq);
  2633. avio_printf(c->pb, "Public: %s\r\n",
  2634. "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE");
  2635. avio_printf(c->pb, "\r\n");
  2636. }
  2637. static void rtsp_cmd_describe(HTTPContext *c, const char *url)
  2638. {
  2639. FFServerStream *stream;
  2640. char path1[1024];
  2641. const char *path;
  2642. uint8_t *content;
  2643. int content_length;
  2644. socklen_t len;
  2645. struct sockaddr_in my_addr;
  2646. /* find which URL is asked */
  2647. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2648. path = path1;
  2649. if (*path == '/')
  2650. path++;
  2651. for(stream = config.first_stream; stream; stream = stream->next) {
  2652. if (!stream->is_feed &&
  2653. stream->fmt && !strcmp(stream->fmt->name, "rtp") &&
  2654. !strcmp(path, stream->filename)) {
  2655. goto found;
  2656. }
  2657. }
  2658. /* no stream found */
  2659. rtsp_reply_error(c, RTSP_STATUS_NOT_FOUND);
  2660. return;
  2661. found:
  2662. /* prepare the media description in SDP format */
  2663. /* get the host IP */
  2664. len = sizeof(my_addr);
  2665. getsockname(c->fd, (struct sockaddr *)&my_addr, &len);
  2666. content_length = prepare_sdp_description(stream, &content,
  2667. my_addr.sin_addr);
  2668. if (content_length < 0) {
  2669. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2670. return;
  2671. }
  2672. rtsp_reply_header(c, RTSP_STATUS_OK);
  2673. avio_printf(c->pb, "Content-Base: %s/\r\n", url);
  2674. avio_printf(c->pb, "Content-Type: application/sdp\r\n");
  2675. avio_printf(c->pb, "Content-Length: %d\r\n", content_length);
  2676. avio_printf(c->pb, "\r\n");
  2677. avio_write(c->pb, content, content_length);
  2678. av_free(content);
  2679. }
  2680. static HTTPContext *find_rtp_session(const char *session_id)
  2681. {
  2682. HTTPContext *c;
  2683. if (session_id[0] == '\0')
  2684. return NULL;
  2685. for(c = first_http_ctx; c; c = c->next) {
  2686. if (!strcmp(c->session_id, session_id))
  2687. return c;
  2688. }
  2689. return NULL;
  2690. }
  2691. static RTSPTransportField *find_transport(RTSPMessageHeader *h, enum RTSPLowerTransport lower_transport)
  2692. {
  2693. RTSPTransportField *th;
  2694. int i;
  2695. for(i=0;i<h->nb_transports;i++) {
  2696. th = &h->transports[i];
  2697. if (th->lower_transport == lower_transport)
  2698. return th;
  2699. }
  2700. return NULL;
  2701. }
  2702. static void rtsp_cmd_setup(HTTPContext *c, const char *url,
  2703. RTSPMessageHeader *h)
  2704. {
  2705. FFServerStream *stream;
  2706. int stream_index, rtp_port, rtcp_port;
  2707. char buf[1024];
  2708. char path1[1024];
  2709. const char *path;
  2710. HTTPContext *rtp_c;
  2711. RTSPTransportField *th;
  2712. struct sockaddr_in dest_addr;
  2713. RTSPActionServerSetup setup;
  2714. /* find which URL is asked */
  2715. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2716. path = path1;
  2717. if (*path == '/')
  2718. path++;
  2719. /* now check each stream */
  2720. for(stream = config.first_stream; stream; stream = stream->next) {
  2721. if (stream->is_feed || !stream->fmt ||
  2722. strcmp(stream->fmt->name, "rtp")) {
  2723. continue;
  2724. }
  2725. /* accept aggregate filenames only if single stream */
  2726. if (!strcmp(path, stream->filename)) {
  2727. if (stream->nb_streams != 1) {
  2728. rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);
  2729. return;
  2730. }
  2731. stream_index = 0;
  2732. goto found;
  2733. }
  2734. for(stream_index = 0; stream_index < stream->nb_streams;
  2735. stream_index++) {
  2736. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2737. stream->filename, stream_index);
  2738. if (!strcmp(path, buf))
  2739. goto found;
  2740. }
  2741. }
  2742. /* no stream found */
  2743. rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */
  2744. return;
  2745. found:
  2746. /* generate session id if needed */
  2747. if (h->session_id[0] == '\0') {
  2748. unsigned random0 = av_lfg_get(&random_state);
  2749. unsigned random1 = av_lfg_get(&random_state);
  2750. snprintf(h->session_id, sizeof(h->session_id), "%08x%08x",
  2751. random0, random1);
  2752. }
  2753. /* find RTP session, and create it if none found */
  2754. rtp_c = find_rtp_session(h->session_id);
  2755. if (!rtp_c) {
  2756. /* always prefer UDP */
  2757. th = find_transport(h, RTSP_LOWER_TRANSPORT_UDP);
  2758. if (!th) {
  2759. th = find_transport(h, RTSP_LOWER_TRANSPORT_TCP);
  2760. if (!th) {
  2761. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2762. return;
  2763. }
  2764. }
  2765. rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,
  2766. th->lower_transport);
  2767. if (!rtp_c) {
  2768. rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);
  2769. return;
  2770. }
  2771. /* open input stream */
  2772. if (open_input_stream(rtp_c, "") < 0) {
  2773. rtsp_reply_error(c, RTSP_STATUS_INTERNAL);
  2774. return;
  2775. }
  2776. }
  2777. /* test if stream is OK (test needed because several SETUP needs
  2778. * to be done for a given file) */
  2779. if (rtp_c->stream != stream) {
  2780. rtsp_reply_error(c, RTSP_STATUS_SERVICE);
  2781. return;
  2782. }
  2783. /* test if stream is already set up */
  2784. if (rtp_c->rtp_ctx[stream_index]) {
  2785. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2786. return;
  2787. }
  2788. /* check transport */
  2789. th = find_transport(h, rtp_c->rtp_protocol);
  2790. if (!th || (th->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
  2791. th->client_port_min <= 0)) {
  2792. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2793. return;
  2794. }
  2795. /* setup default options */
  2796. setup.transport_option[0] = '\0';
  2797. dest_addr = rtp_c->from_addr;
  2798. dest_addr.sin_port = htons(th->client_port_min);
  2799. /* setup stream */
  2800. if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {
  2801. rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);
  2802. return;
  2803. }
  2804. /* now everything is OK, so we can send the connection parameters */
  2805. rtsp_reply_header(c, RTSP_STATUS_OK);
  2806. /* session ID */
  2807. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2808. switch(rtp_c->rtp_protocol) {
  2809. case RTSP_LOWER_TRANSPORT_UDP:
  2810. rtp_port = ff_rtp_get_local_rtp_port(rtp_c->rtp_handles[stream_index]);
  2811. rtcp_port = ff_rtp_get_local_rtcp_port(rtp_c->rtp_handles[stream_index]);
  2812. avio_printf(c->pb, "Transport: RTP/AVP/UDP;unicast;"
  2813. "client_port=%d-%d;server_port=%d-%d",
  2814. th->client_port_min, th->client_port_max,
  2815. rtp_port, rtcp_port);
  2816. break;
  2817. case RTSP_LOWER_TRANSPORT_TCP:
  2818. avio_printf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d",
  2819. stream_index * 2, stream_index * 2 + 1);
  2820. break;
  2821. default:
  2822. break;
  2823. }
  2824. if (setup.transport_option[0] != '\0')
  2825. avio_printf(c->pb, ";%s", setup.transport_option);
  2826. avio_printf(c->pb, "\r\n");
  2827. avio_printf(c->pb, "\r\n");
  2828. }
  2829. /**
  2830. * find an RTP connection by using the session ID. Check consistency
  2831. * with filename
  2832. */
  2833. static HTTPContext *find_rtp_session_with_url(const char *url,
  2834. const char *session_id)
  2835. {
  2836. HTTPContext *rtp_c;
  2837. char path1[1024];
  2838. const char *path;
  2839. char buf[1024];
  2840. int s, len;
  2841. rtp_c = find_rtp_session(session_id);
  2842. if (!rtp_c)
  2843. return NULL;
  2844. /* find which URL is asked */
  2845. av_url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);
  2846. path = path1;
  2847. if (*path == '/')
  2848. path++;
  2849. if(!strcmp(path, rtp_c->stream->filename)) return rtp_c;
  2850. for(s=0; s<rtp_c->stream->nb_streams; ++s) {
  2851. snprintf(buf, sizeof(buf), "%s/streamid=%d",
  2852. rtp_c->stream->filename, s);
  2853. if(!strncmp(path, buf, sizeof(buf)))
  2854. /* XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE
  2855. * if nb_streams>1? */
  2856. return rtp_c;
  2857. }
  2858. len = strlen(path);
  2859. if (len > 0 && path[len - 1] == '/' &&
  2860. !strncmp(path, rtp_c->stream->filename, len - 1))
  2861. return rtp_c;
  2862. return NULL;
  2863. }
  2864. static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPMessageHeader *h)
  2865. {
  2866. HTTPContext *rtp_c;
  2867. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2868. if (!rtp_c) {
  2869. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2870. return;
  2871. }
  2872. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2873. rtp_c->state != HTTPSTATE_WAIT_FEED &&
  2874. rtp_c->state != HTTPSTATE_READY) {
  2875. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2876. return;
  2877. }
  2878. rtp_c->state = HTTPSTATE_SEND_DATA;
  2879. /* now everything is OK, so we can send the connection parameters */
  2880. rtsp_reply_header(c, RTSP_STATUS_OK);
  2881. /* session ID */
  2882. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2883. avio_printf(c->pb, "\r\n");
  2884. }
  2885. static void rtsp_cmd_interrupt(HTTPContext *c, const char *url,
  2886. RTSPMessageHeader *h, int pause_only)
  2887. {
  2888. HTTPContext *rtp_c;
  2889. rtp_c = find_rtp_session_with_url(url, h->session_id);
  2890. if (!rtp_c) {
  2891. rtsp_reply_error(c, RTSP_STATUS_SESSION);
  2892. return;
  2893. }
  2894. if (pause_only) {
  2895. if (rtp_c->state != HTTPSTATE_SEND_DATA &&
  2896. rtp_c->state != HTTPSTATE_WAIT_FEED) {
  2897. rtsp_reply_error(c, RTSP_STATUS_STATE);
  2898. return;
  2899. }
  2900. rtp_c->state = HTTPSTATE_READY;
  2901. rtp_c->first_pts = AV_NOPTS_VALUE;
  2902. }
  2903. /* now everything is OK, so we can send the connection parameters */
  2904. rtsp_reply_header(c, RTSP_STATUS_OK);
  2905. /* session ID */
  2906. avio_printf(c->pb, "Session: %s\r\n", rtp_c->session_id);
  2907. avio_printf(c->pb, "\r\n");
  2908. if (!pause_only)
  2909. close_connection(rtp_c);
  2910. }
  2911. /********************************************************************/
  2912. /* RTP handling */
  2913. static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr,
  2914. FFServerStream *stream,
  2915. const char *session_id,
  2916. enum RTSPLowerTransport rtp_protocol)
  2917. {
  2918. HTTPContext *c = NULL;
  2919. const char *proto_str;
  2920. /* XXX: should output a warning page when coming
  2921. * close to the connection limit */
  2922. if (nb_connections >= config.nb_max_connections)
  2923. goto fail;
  2924. /* add a new connection */
  2925. c = av_mallocz(sizeof(HTTPContext));
  2926. if (!c)
  2927. goto fail;
  2928. c->fd = -1;
  2929. c->poll_entry = NULL;
  2930. c->from_addr = *from_addr;
  2931. c->buffer_size = IOBUFFER_INIT_SIZE;
  2932. c->buffer = av_malloc(c->buffer_size);
  2933. if (!c->buffer)
  2934. goto fail;
  2935. nb_connections++;
  2936. c->stream = stream;
  2937. av_strlcpy(c->session_id, session_id, sizeof(c->session_id));
  2938. c->state = HTTPSTATE_READY;
  2939. c->is_packetized = 1;
  2940. c->rtp_protocol = rtp_protocol;
  2941. /* protocol is shown in statistics */
  2942. switch(c->rtp_protocol) {
  2943. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  2944. proto_str = "MCAST";
  2945. break;
  2946. case RTSP_LOWER_TRANSPORT_UDP:
  2947. proto_str = "UDP";
  2948. break;
  2949. case RTSP_LOWER_TRANSPORT_TCP:
  2950. proto_str = "TCP";
  2951. break;
  2952. default:
  2953. proto_str = "???";
  2954. break;
  2955. }
  2956. av_strlcpy(c->protocol, "RTP/", sizeof(c->protocol));
  2957. av_strlcat(c->protocol, proto_str, sizeof(c->protocol));
  2958. current_bandwidth += stream->bandwidth;
  2959. c->next = first_http_ctx;
  2960. first_http_ctx = c;
  2961. return c;
  2962. fail:
  2963. if (c) {
  2964. av_freep(&c->buffer);
  2965. av_free(c);
  2966. }
  2967. return NULL;
  2968. }
  2969. /**
  2970. * add a new RTP stream in an RTP connection (used in RTSP SETUP
  2971. * command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is
  2972. * used.
  2973. */
  2974. static int rtp_new_av_stream(HTTPContext *c,
  2975. int stream_index, struct sockaddr_in *dest_addr,
  2976. HTTPContext *rtsp_c)
  2977. {
  2978. AVFormatContext *ctx;
  2979. AVStream *st;
  2980. char *ipaddr;
  2981. URLContext *h = NULL;
  2982. uint8_t *dummy_buf;
  2983. int max_packet_size;
  2984. void *st_internal;
  2985. /* now we can open the relevant output stream */
  2986. ctx = avformat_alloc_context();
  2987. if (!ctx)
  2988. return -1;
  2989. ctx->oformat = av_guess_format("rtp", NULL, NULL);
  2990. st = avformat_new_stream(ctx, NULL);
  2991. if (!st)
  2992. goto fail;
  2993. av_freep(&st->codec);
  2994. av_freep(&st->info);
  2995. st_internal = st->internal;
  2996. if (!c->stream->feed ||
  2997. c->stream->feed == c->stream)
  2998. memcpy(st, c->stream->streams[stream_index], sizeof(AVStream));
  2999. else
  3000. memcpy(st,
  3001. c->stream->feed->streams[c->stream->feed_streams[stream_index]],
  3002. sizeof(AVStream));
  3003. st->priv_data = NULL;
  3004. st->internal = st_internal;
  3005. /* build destination RTP address */
  3006. ipaddr = inet_ntoa(dest_addr->sin_addr);
  3007. switch(c->rtp_protocol) {
  3008. case RTSP_LOWER_TRANSPORT_UDP:
  3009. case RTSP_LOWER_TRANSPORT_UDP_MULTICAST:
  3010. /* RTP/UDP case */
  3011. /* XXX: also pass as parameter to function ? */
  3012. if (c->stream->is_multicast) {
  3013. int ttl;
  3014. ttl = c->stream->multicast_ttl;
  3015. if (!ttl)
  3016. ttl = 16;
  3017. snprintf(ctx->filename, sizeof(ctx->filename),
  3018. "rtp://%s:%d?multicast=1&ttl=%d",
  3019. ipaddr, ntohs(dest_addr->sin_port), ttl);
  3020. } else {
  3021. snprintf(ctx->filename, sizeof(ctx->filename),
  3022. "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port));
  3023. }
  3024. if (ffurl_open(&h, ctx->filename, AVIO_FLAG_WRITE, NULL, NULL) < 0)
  3025. goto fail;
  3026. c->rtp_handles[stream_index] = h;
  3027. max_packet_size = h->max_packet_size;
  3028. break;
  3029. case RTSP_LOWER_TRANSPORT_TCP:
  3030. /* RTP/TCP case */
  3031. c->rtsp_c = rtsp_c;
  3032. max_packet_size = RTSP_TCP_MAX_PACKET_SIZE;
  3033. break;
  3034. default:
  3035. goto fail;
  3036. }
  3037. http_log("%s:%d - - \"PLAY %s/streamid=%d %s\"\n",
  3038. ipaddr, ntohs(dest_addr->sin_port),
  3039. c->stream->filename, stream_index, c->protocol);
  3040. /* normally, no packets should be output here, but the packet size may
  3041. * be checked */
  3042. if (ffio_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0)
  3043. /* XXX: close stream */
  3044. goto fail;
  3045. if (avformat_write_header(ctx, NULL) < 0) {
  3046. fail:
  3047. if (h)
  3048. ffurl_close(h);
  3049. av_free(st);
  3050. av_free(ctx);
  3051. return -1;
  3052. }
  3053. avio_close_dyn_buf(ctx->pb, &dummy_buf);
  3054. ctx->pb = NULL;
  3055. av_free(dummy_buf);
  3056. c->rtp_ctx[stream_index] = ctx;
  3057. return 0;
  3058. }
  3059. /********************************************************************/
  3060. /* ffserver initialization */
  3061. /* FIXME: This code should use avformat_new_stream() */
  3062. static AVStream *add_av_stream1(FFServerStream *stream,
  3063. AVCodecContext *codec, int copy)
  3064. {
  3065. AVStream *fst;
  3066. if(stream->nb_streams >= FF_ARRAY_ELEMS(stream->streams))
  3067. return NULL;
  3068. fst = av_mallocz(sizeof(AVStream));
  3069. if (!fst)
  3070. return NULL;
  3071. if (copy) {
  3072. fst->codec = avcodec_alloc_context3(codec->codec);
  3073. if (!fst->codec) {
  3074. av_free(fst);
  3075. return NULL;
  3076. }
  3077. avcodec_copy_context(fst->codec, codec);
  3078. } else
  3079. /* live streams must use the actual feed's codec since it may be
  3080. * updated later to carry extradata needed by them.
  3081. */
  3082. fst->codec = codec;
  3083. fst->priv_data = av_mallocz(sizeof(FeedData));
  3084. fst->internal = av_mallocz(sizeof(*fst->internal));
  3085. fst->index = stream->nb_streams;
  3086. avpriv_set_pts_info(fst, 33, 1, 90000);
  3087. fst->sample_aspect_ratio = codec->sample_aspect_ratio;
  3088. stream->streams[stream->nb_streams++] = fst;
  3089. return fst;
  3090. }
  3091. /* return the stream number in the feed */
  3092. static int add_av_stream(FFServerStream *feed, AVStream *st)
  3093. {
  3094. AVStream *fst;
  3095. AVCodecContext *av, *av1;
  3096. int i;
  3097. av = st->codec;
  3098. for(i=0;i<feed->nb_streams;i++) {
  3099. av1 = feed->streams[i]->codec;
  3100. if (av1->codec_id == av->codec_id &&
  3101. av1->codec_type == av->codec_type &&
  3102. av1->bit_rate == av->bit_rate) {
  3103. switch(av->codec_type) {
  3104. case AVMEDIA_TYPE_AUDIO:
  3105. if (av1->channels == av->channels &&
  3106. av1->sample_rate == av->sample_rate)
  3107. return i;
  3108. break;
  3109. case AVMEDIA_TYPE_VIDEO:
  3110. if (av1->width == av->width &&
  3111. av1->height == av->height &&
  3112. av1->time_base.den == av->time_base.den &&
  3113. av1->time_base.num == av->time_base.num &&
  3114. av1->gop_size == av->gop_size)
  3115. return i;
  3116. break;
  3117. default:
  3118. abort();
  3119. }
  3120. }
  3121. }
  3122. fst = add_av_stream1(feed, av, 0);
  3123. if (!fst)
  3124. return -1;
  3125. if (av_stream_get_recommended_encoder_configuration(st))
  3126. av_stream_set_recommended_encoder_configuration(fst,
  3127. av_strdup(av_stream_get_recommended_encoder_configuration(st)));
  3128. return feed->nb_streams - 1;
  3129. }
  3130. static void remove_stream(FFServerStream *stream)
  3131. {
  3132. FFServerStream **ps;
  3133. ps = &config.first_stream;
  3134. while (*ps) {
  3135. if (*ps == stream)
  3136. *ps = (*ps)->next;
  3137. else
  3138. ps = &(*ps)->next;
  3139. }
  3140. }
  3141. /* specific MPEG4 handling : we extract the raw parameters */
  3142. static void extract_mpeg4_header(AVFormatContext *infile)
  3143. {
  3144. int mpeg4_count, i, size;
  3145. AVPacket pkt;
  3146. AVStream *st;
  3147. const uint8_t *p;
  3148. infile->flags |= AVFMT_FLAG_NOFILLIN | AVFMT_FLAG_NOPARSE;
  3149. mpeg4_count = 0;
  3150. for(i=0;i<infile->nb_streams;i++) {
  3151. st = infile->streams[i];
  3152. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3153. st->codec->extradata_size == 0) {
  3154. mpeg4_count++;
  3155. }
  3156. }
  3157. if (!mpeg4_count)
  3158. return;
  3159. printf("MPEG4 without extra data: trying to find header in %s\n",
  3160. infile->filename);
  3161. while (mpeg4_count > 0) {
  3162. if (av_read_frame(infile, &pkt) < 0)
  3163. break;
  3164. st = infile->streams[pkt.stream_index];
  3165. if (st->codec->codec_id == AV_CODEC_ID_MPEG4 &&
  3166. st->codec->extradata_size == 0) {
  3167. av_freep(&st->codec->extradata);
  3168. /* fill extradata with the header */
  3169. /* XXX: we make hard suppositions here ! */
  3170. p = pkt.data;
  3171. while (p < pkt.data + pkt.size - 4) {
  3172. /* stop when vop header is found */
  3173. if (p[0] == 0x00 && p[1] == 0x00 &&
  3174. p[2] == 0x01 && p[3] == 0xb6) {
  3175. size = p - pkt.data;
  3176. st->codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
  3177. st->codec->extradata_size = size;
  3178. memcpy(st->codec->extradata, pkt.data, size);
  3179. break;
  3180. }
  3181. p++;
  3182. }
  3183. mpeg4_count--;
  3184. }
  3185. av_packet_unref(&pkt);
  3186. }
  3187. }
  3188. /* compute the needed AVStream for each file */
  3189. static void build_file_streams(void)
  3190. {
  3191. FFServerStream *stream;
  3192. AVFormatContext *infile;
  3193. int i, ret;
  3194. /* gather all streams */
  3195. for(stream = config.first_stream; stream; stream = stream->next) {
  3196. infile = NULL;
  3197. if (stream->stream_type != STREAM_TYPE_LIVE || stream->feed)
  3198. continue;
  3199. /* the stream comes from a file */
  3200. /* try to open the file */
  3201. /* open stream */
  3202. /* specific case: if transport stream output to RTP,
  3203. * we use a raw transport stream reader */
  3204. if (stream->fmt && !strcmp(stream->fmt->name, "rtp"))
  3205. av_dict_set(&stream->in_opts, "mpeg2ts_compute_pcr", "1", 0);
  3206. if (!stream->feed_filename[0]) {
  3207. http_log("Unspecified feed file for stream '%s'\n",
  3208. stream->filename);
  3209. goto fail;
  3210. }
  3211. http_log("Opening feed file '%s' for stream '%s'\n",
  3212. stream->feed_filename, stream->filename);
  3213. ret = avformat_open_input(&infile, stream->feed_filename,
  3214. stream->ifmt, &stream->in_opts);
  3215. if (ret < 0) {
  3216. http_log("Could not open '%s': %s\n", stream->feed_filename,
  3217. av_err2str(ret));
  3218. /* remove stream (no need to spend more time on it) */
  3219. fail:
  3220. remove_stream(stream);
  3221. } else {
  3222. /* find all the AVStreams inside and reference them in
  3223. * 'stream' */
  3224. if (avformat_find_stream_info(infile, NULL) < 0) {
  3225. http_log("Could not find codec parameters from '%s'\n",
  3226. stream->feed_filename);
  3227. avformat_close_input(&infile);
  3228. goto fail;
  3229. }
  3230. extract_mpeg4_header(infile);
  3231. for(i=0;i<infile->nb_streams;i++)
  3232. add_av_stream1(stream, infile->streams[i]->codec, 1);
  3233. avformat_close_input(&infile);
  3234. }
  3235. }
  3236. }
  3237. static inline
  3238. int check_codec_match(AVCodecContext *ccf, AVCodecContext *ccs, int stream)
  3239. {
  3240. int matches = 1;
  3241. #define CHECK_CODEC(x) (ccf->x != ccs->x)
  3242. if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {
  3243. http_log("Codecs do not match for stream %d\n", stream);
  3244. matches = 0;
  3245. } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {
  3246. http_log("Codec bitrates do not match for stream %d\n", stream);
  3247. matches = 0;
  3248. } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {
  3249. if (CHECK_CODEC(time_base.den) ||
  3250. CHECK_CODEC(time_base.num) ||
  3251. CHECK_CODEC(width) ||
  3252. CHECK_CODEC(height)) {
  3253. http_log("Codec width, height or framerate do not match for stream %d\n", stream);
  3254. matches = 0;
  3255. }
  3256. } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {
  3257. if (CHECK_CODEC(sample_rate) ||
  3258. CHECK_CODEC(channels) ||
  3259. CHECK_CODEC(frame_size)) {
  3260. http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", stream);
  3261. matches = 0;
  3262. }
  3263. } else {
  3264. http_log("Unknown codec type for stream %d\n", stream);
  3265. matches = 0;
  3266. }
  3267. return matches;
  3268. }
  3269. /* compute the needed AVStream for each feed */
  3270. static int build_feed_streams(void)
  3271. {
  3272. FFServerStream *stream, *feed;
  3273. int i, fd;
  3274. /* gather all streams */
  3275. for(stream = config.first_stream; stream; stream = stream->next) {
  3276. feed = stream->feed;
  3277. if (!feed)
  3278. continue;
  3279. if (stream->is_feed) {
  3280. for(i=0;i<stream->nb_streams;i++)
  3281. stream->feed_streams[i] = i;
  3282. continue;
  3283. }
  3284. /* we handle a stream coming from a feed */
  3285. for(i=0;i<stream->nb_streams;i++)
  3286. stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]);
  3287. }
  3288. /* create feed files if needed */
  3289. for(feed = config.first_feed; feed; feed = feed->next_feed) {
  3290. if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {
  3291. AVFormatContext *s = NULL;
  3292. int matches = 0;
  3293. /* See if it matches */
  3294. if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) < 0) {
  3295. http_log("Deleting feed file '%s' as it appears "
  3296. "to be corrupt\n",
  3297. feed->feed_filename);
  3298. goto drop;
  3299. }
  3300. /* set buffer size */
  3301. if (ffio_set_buf_size(s->pb, FFM_PACKET_SIZE) < 0) {
  3302. http_log("Failed to set buffer size\n");
  3303. avformat_close_input(&s);
  3304. goto bail;
  3305. }
  3306. /* Now see if it matches */
  3307. if (s->nb_streams != feed->nb_streams) {
  3308. http_log("Deleting feed file '%s' as stream counts "
  3309. "differ (%d != %d)\n",
  3310. feed->feed_filename, s->nb_streams, feed->nb_streams);
  3311. goto drop;
  3312. }
  3313. matches = 1;
  3314. for(i=0;i<s->nb_streams;i++) {
  3315. AVStream *sf, *ss;
  3316. sf = feed->streams[i];
  3317. ss = s->streams[i];
  3318. if (sf->index != ss->index || sf->id != ss->id) {
  3319. http_log("Index & Id do not match for stream %d (%s)\n",
  3320. i, feed->feed_filename);
  3321. matches = 0;
  3322. break;
  3323. }
  3324. matches = check_codec_match (sf->codec, ss->codec, i);
  3325. if (!matches)
  3326. break;
  3327. }
  3328. drop:
  3329. if (s)
  3330. avformat_close_input(&s);
  3331. if (!matches) {
  3332. if (feed->readonly) {
  3333. http_log("Unable to delete read-only feed file '%s'\n",
  3334. feed->feed_filename);
  3335. goto bail;
  3336. }
  3337. unlink(feed->feed_filename);
  3338. }
  3339. }
  3340. if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {
  3341. AVFormatContext *s = avformat_alloc_context();
  3342. if (!s) {
  3343. http_log("Failed to allocate context\n");
  3344. goto bail;
  3345. }
  3346. if (feed->readonly) {
  3347. http_log("Unable to create feed file '%s' as it is "
  3348. "marked readonly\n",
  3349. feed->feed_filename);
  3350. avformat_free_context(s);
  3351. goto bail;
  3352. }
  3353. /* only write the header of the ffm file */
  3354. if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {
  3355. http_log("Could not open output feed file '%s'\n",
  3356. feed->feed_filename);
  3357. avformat_free_context(s);
  3358. goto bail;
  3359. }
  3360. s->oformat = feed->fmt;
  3361. s->nb_streams = feed->nb_streams;
  3362. s->streams = feed->streams;
  3363. if (avformat_write_header(s, NULL) < 0) {
  3364. http_log("Container doesn't support the required parameters\n");
  3365. avio_closep(&s->pb);
  3366. s->streams = NULL;
  3367. s->nb_streams = 0;
  3368. avformat_free_context(s);
  3369. goto bail;
  3370. }
  3371. /* XXX: need better API */
  3372. av_freep(&s->priv_data);
  3373. avio_closep(&s->pb);
  3374. s->streams = NULL;
  3375. s->nb_streams = 0;
  3376. avformat_free_context(s);
  3377. }
  3378. /* get feed size and write index */
  3379. fd = open(feed->feed_filename, O_RDONLY);
  3380. if (fd < 0) {
  3381. http_log("Could not open output feed file '%s'\n",
  3382. feed->feed_filename);
  3383. goto bail;
  3384. }
  3385. feed->feed_write_index = FFMAX(ffm_read_write_index(fd),
  3386. FFM_PACKET_SIZE);
  3387. feed->feed_size = lseek(fd, 0, SEEK_END);
  3388. /* ensure that we do not wrap before the end of file */
  3389. if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)
  3390. feed->feed_max_size = feed->feed_size;
  3391. close(fd);
  3392. }
  3393. return 0;
  3394. bail:
  3395. return -1;
  3396. }
  3397. /* compute the bandwidth used by each stream */
  3398. static void compute_bandwidth(void)
  3399. {
  3400. unsigned bandwidth;
  3401. int i;
  3402. FFServerStream *stream;
  3403. for(stream = config.first_stream; stream; stream = stream->next) {
  3404. bandwidth = 0;
  3405. for(i=0;i<stream->nb_streams;i++) {
  3406. AVStream *st = stream->streams[i];
  3407. switch(st->codec->codec_type) {
  3408. case AVMEDIA_TYPE_AUDIO:
  3409. case AVMEDIA_TYPE_VIDEO:
  3410. bandwidth += st->codec->bit_rate;
  3411. break;
  3412. default:
  3413. break;
  3414. }
  3415. }
  3416. stream->bandwidth = (bandwidth + 999) / 1000;
  3417. }
  3418. }
  3419. static void handle_child_exit(int sig)
  3420. {
  3421. pid_t pid;
  3422. int status;
  3423. time_t uptime;
  3424. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  3425. FFServerStream *feed;
  3426. for (feed = config.first_feed; feed; feed = feed->next) {
  3427. if (feed->pid != pid)
  3428. continue;
  3429. uptime = time(0) - feed->pid_start;
  3430. feed->pid = 0;
  3431. fprintf(stderr,
  3432. "%s: Pid %"PRId64" exited with status %d after %"PRId64" "
  3433. "seconds\n",
  3434. feed->filename, (int64_t) pid, status, (int64_t)uptime);
  3435. if (uptime < 30)
  3436. /* Turn off any more restarts */
  3437. ffserver_free_child_args(&feed->child_argv);
  3438. }
  3439. }
  3440. need_to_start_children = 1;
  3441. }
  3442. static void opt_debug(void)
  3443. {
  3444. config.debug = 1;
  3445. snprintf(config.logfilename, sizeof(config.logfilename), "-");
  3446. }
  3447. void show_help_default(const char *opt, const char *arg)
  3448. {
  3449. printf("usage: ffserver [options]\n"
  3450. "Hyper fast multi format Audio/Video streaming server\n");
  3451. printf("\n");
  3452. show_help_options(options, "Main options:", 0, 0, 0);
  3453. }
  3454. static const OptionDef options[] = {
  3455. #include "cmdutils_common_opts.h"
  3456. { "n", OPT_BOOL, {(void *)&no_launch }, "enable no-launch mode" },
  3457. { "d", 0, {(void*)opt_debug}, "enable debug mode" },
  3458. { "f", HAS_ARG | OPT_STRING, {(void*)&config.filename }, "use configfile instead of /etc/ffserver.conf", "configfile" },
  3459. { NULL },
  3460. };
  3461. int main(int argc, char **argv)
  3462. {
  3463. struct sigaction sigact = { { 0 } };
  3464. int cfg_parsed;
  3465. int ret = EXIT_FAILURE;
  3466. init_dynload();
  3467. config.filename = av_strdup("/etc/ffserver.conf");
  3468. parse_loglevel(argc, argv, options);
  3469. av_register_all();
  3470. avformat_network_init();
  3471. show_banner(argc, argv, options);
  3472. my_program_name = argv[0];
  3473. parse_options(NULL, argc, argv, options, NULL);
  3474. unsetenv("http_proxy"); /* Kill the http_proxy */
  3475. av_lfg_init(&random_state, av_get_random_seed());
  3476. sigact.sa_handler = handle_child_exit;
  3477. sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART;
  3478. sigaction(SIGCHLD, &sigact, 0);
  3479. if ((cfg_parsed = ffserver_parse_ffconfig(config.filename, &config)) < 0) {
  3480. fprintf(stderr, "Error reading configuration file '%s': %s\n",
  3481. config.filename, av_err2str(cfg_parsed));
  3482. goto bail;
  3483. }
  3484. /* open log file if needed */
  3485. if (config.logfilename[0] != '\0') {
  3486. if (!strcmp(config.logfilename, "-"))
  3487. logfile = stdout;
  3488. else
  3489. logfile = fopen(config.logfilename, "a");
  3490. av_log_set_callback(http_av_log);
  3491. }
  3492. build_file_streams();
  3493. if (build_feed_streams() < 0) {
  3494. http_log("Could not setup feed streams\n");
  3495. goto bail;
  3496. }
  3497. compute_bandwidth();
  3498. /* signal init */
  3499. signal(SIGPIPE, SIG_IGN);
  3500. if (http_server() < 0) {
  3501. http_log("Could not start server\n");
  3502. goto bail;
  3503. }
  3504. ret=EXIT_SUCCESS;
  3505. bail:
  3506. av_freep (&config.filename);
  3507. avformat_network_deinit();
  3508. return ret;
  3509. }