ffserver.c 126 KB

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