ffserver.c 123 KB

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